Проверяем открытость порта в Windows 7 при помощи PowerShell и командлета Test-NetConnection
Всем привет, с вами Александр Глебов. В этой статье я рассказываю, как проверить порт через PowerShell на Windows 7 при помощи командлета Test-NetConnection. Очень часто требуется проверить открытость порта, на каком либо компьютере. Решить эту задачу можно несколькими способами…
Собственно самый популярный способ как проверить открытость порта это юзать команду telnet. Простейший пример проверки порта через телнет:
telnet yandex.ru 80
В результате в командной строке произойдет подключение, значит порт 80 у яндекса открыт.
Но у телнета есть огромный минус, а именно в не зависимости установилось ли подключение по порту или нет команда всегда возвращает 0. А это значит, что telnet не удастся использовать в скриптах, так как конструкцию IF Then Else уже не построишь.
Для решения проблемы можно использовать командлет Test-NetConnection, но на Windows 7 придется пошаманить…
Корпорация Microsoft конечно молодцы, они в PowerShell версии 4.0 добавил модуль NetTCPIP, но самое смешное, что этот модуль есть только в PowerShell 5 на Windows 8.1 и Windows 2012 R2. И даже если скачать отдельно PowerShell 4.0 или 5.0 там этого модуля не будет.
Но если взять бубен, набраться терпения, то можно подключить этот модуль ручками. Итак, для этого выполним следующие шаги:
- Сперва необходимо установить PowerShell 5.0 для Windows 7. Скачать можно отсюда.
- Для начала убедимся, что командлет Test-NetConnection у нас не работает. Выполним команду Test-NetConnection:
- Как видим командлет не подцепился. Для его работы необходимо импортировать модуль работы с сетью, для этого скачиваем архив NetTCPIP.zip.
- Распаковываем архив (в архиве папка NetTCPIP, DnsClient, NetSecurity ) в папку Modules: C:\Windows\System32\WindowsPowerShell\v1.0\Modules\
- Открываем PowerShell x64 от имени администратора.
- Импортируем модуль NetTCPIP командой: Import-Module -Name C:\Windows\System32\WindowsPowerShell\v1.0\Modules\NetTCPIP -Verbose
- Все, мы подключили три модуля NetTCPIP, DnsClient, NetSecurity и можешь пользоваться командлетом Test-NetConnection.
- Проверим 80 порт у яндекса, открыт или нет. Результат работы команды:
TcpTestSucceeded = True означает, что 80-ый порт у yandex.ru открыт. Как видим команда успешно работает, возвращает True или False и ее можно использовать в своих скриптах.
На этом заканчиваю данную стать, в ней я ответил на вопрос как проверить порт через PowerShell на Windows 7. Как выяснилось это довольно просто. Если остались вопросы, замечания, предложения то пишите в комментариях. Буду рад обсудить.
Загрузка…
Интересные статьи по теме:
В PowerShell для проверки доступности порта на удаленном компьютере можно использовать командлет Test-NetConnection. Этот командлет позволяет проверить доступность удаленного сервера или службы на нем, протестировать блокируется ли TCP порт файерволами, проверить доступность по ICMP и маршрутизацию. По сути, командлет Test-NetConnection позволяет заменить сразу несколько привычных сетевых утилит: ping, traceroute, telnet, сканер TCP портов и т.д.
Содержание:
- Проверка доступности TCP порта с помощью Test-NetConnection
- PowerShell: проверка открытых портов на нескольких IP хостах
- IP сканер сети на PowerShell
- Вывести список открытых портов в Windows
Проверка доступности TCP порта с помощью Test-NetConnection
Командлет Test-NetConnection можно использовать только для проверки TCP портов. Например, чтобы проверить, что на почтовом сервере открыт порт TCP 25 (SMTP протокол), выполните команду:
Test-NetConnection -ComputerName msk-msg01 -Port 25
Примечание. С помощью командлета Test-NetConnection можно проверить только TCP соединение, для проверки доступности UDP портов он не применим.
В сокращенном виде аналогичная команда выглядит так:
TNC msk-mail1 -Port 25
Разберем результат команды:
ComputerName : msk-msg01 RemoteAddress : 10.10.1.7 RemotePort : 25 InterfaceAlias : CORP SourceAddress : 10.10.1.70 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : True
Как вы видите, командлет выполняет разрешение имени сервера в IP адрес, выполняется проверка ответа ICMP (аналог ping) и проверка ответа от TCP порта (доступность). Указанный сервер доступен по ICMP (
PingSucceeded = True
) и 25 TCP порт также отвечает (
RemotePort=25, TcpTestSucceeded= True
).
Примечание. Если команда вернула PingSucceeded=False и TcpTestSucceeded= True, скорее всего означает, что на удаленном сервере запрещен ICMP Ping.
Если выполнить команду Test-NetConnection без параметров, выполнится проверка наличия подключения к интернету на компьютере (проверяется доступность узла internetbeacon.msedge.net):
Для вывода детальной информации при проверки удаленного TCP порта можно добавить опцию -InformationLevel Detailed:
TNC 192.168.31.102 -Port 3389 -InformationLevel Detailed
Доступность популярных сервисов Windows на удаленном компьютере (HTTP, RDP, SMB, WINRM) можно проверить с помощью параметра CommonTCPPort.
Например, чтобы проверить доступность веб-сервера, можно использовать команду:
Test-NetConnection -ComputerName winitpro.ru -CommonTCPPort HTTP
Или проверить доступность стандартного RDP порта (TCP/3389):
Test-NetConnection msk-rds1 –CommonTCPPort RDP
Можно вывести все параметры, которые возвращает командлет Test-NetConnection:
Test-NetConnection msk-man01 -port 445|Format-List *
Если нужна только информация по доступности TCP порта, в более лаконичном виде проверка может быть выполнена так:
TNC msk-mail1 -Port 25 -InformationLevel Quiet
Командлет вернул True, значит удаленный порт доступен.
Совет. В предыдущих версиях Windows PowerShell (до версии 4.0) проверить доступность удаленного TCP порта можно было так:
(New-Object System.Net.Sockets.TcpClient).Connect('msk-msg01', 25)
Командлет Test-NetConnection можно использовать для трассировки маршрута до удаленного сервера при помощи параметра –TraceRoute (аналог команды трассировки маршрута tracert). С помощью параметра –Hops можно ограничить максимальное количество хопов при проверке.
Test-NetConnection msk-man01 –TraceRoute
Командлет вернул сетевую задержку при доступе к серверу в миллисекундах (
PingReplyDetails (RTT) : 41 ms
) и все IP адреса маршрутизаторов на пути до целевого сервера.
PowerShell: проверка открытых портов на нескольких IP хостах
С помощью PowerShell можно проверить доступность определенного порта на нескольких компьютерах. Сохраните список серверов или IP адресов в текстовый файл servers.txt.
Например, ваша задача – найти сервере на которых не отвечает или закрыт порт TCP/25:
Get-Content c:\Distr\servers.txt | where { -NOT (Test-Netconnection $_ -Port 25 -InformationLevel Quiet)}| Format-Table –AutoSize
Вы можете использовать PowerShell в качестве простейшую систему мониторинга, которая проверяет доступность серверов и выводит уведомление, если один из серверов недоступен.
Например, вы можете проверить доступность основных служб на всех контроллерах домена в AD (список DC можно получить командлетом Get-ADDomainController). Проверим следующие службы на DC (в утилите PortQry есть аналогичное правило Domain and trusts):
- RPC – TCP/135
- LDAP – TCP/389
- LDAP – TCP/3268
- DNS – TCP/53
- Kerberos – TCP/88
- SMB – TCP/445
$Ports = "135","389","636","3268","53","88","445","3269", "80", "443"
$AllDCs = Get-ADDomainController -Filter * | Select-Object Hostname,Ipv4address
ForEach($DC in $AllDCs){
Foreach ($P in $Ports){
$check=Test-NetConnection $DC.Ipv4address -Port $P -WarningAction SilentlyContinue
If ($check.tcpTestSucceeded -eq $true)
{Write-Host $DC.hostname $P -ForegroundColor Green -Separator " => "}
else
{Write-Host $DC.hostname $P -Separator " => " -ForegroundColor Red}
}
}
Скрипт проверит указанные TCP порты на контроллерах домена, и, если один из портов недоступен, выделит его красным цветом (можно запустить данный PowerShell скрипт как службу Windows).
IP сканер сети на PowerShell
Вы можете реализовать простой IP сканер, которые сканирует удаленные хосты или IP подсети на открытые/закрытые TCP порты.
Чтобы просканировать диапазон IP адресов с 10.10.10.5 до 10.10.10.30 и вывести компьютеры, на которых открыт порт 3389:
foreach ($ip in 5..30) {Test-NetConnection -Port 3389 -InformationLevel "Detailed" 10.10.10.$ip}
Можно просканировать диапазон TCP портов (от 1 до 1024) на указанном сервере:
foreach ($port in 1..1024) {If (($a=Test-NetConnection srvfs01 -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}
Вывести список открытых портов в Windows
Если вам нужно вывести список портов, открытых на локальном компьютере, исопльзуется командлет Get-NetTCPConnection (это PowerShell-эквивалент NETSTAT). Полный список открытых портов на компьютере можно вывести так:
Get-NetTcpConnection -State Listen | Select-Object LocalAddress,LocalPort| Sort-Object -Property LocalPort | Format-Table
Если вам нужно проверить, какая программа (процесс) слушает определенный порт на вашем компьютере, выполните команду:
Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess | ft Id, ProcessName, UserName, Path
With Windows 8.1 and Windows Server 2012, R2 Microsoft released PowerShell v4 with new PowerShell modules and new PowerShell cmdlets. One of them is the new Test-NetConnection cmdlet, which does replace some simple network tools like Ping, Traceroute, port scanner, and more.
First, if you just run Test-NetConnection, this will check a Microsoft edge server and will tell you if your internet is working or not.
You can also ping other servers.
If we have a closer look at this cmdlet, we can see that we can do much more.
What we can do is something like a port scan. In this example, I check if the RDP port is open on my webserver. Which is hopefully not
Test-NetConnection thomasmaurer.ch -CommonTCPPort RDP
You can also check for not so common ports by using the -Port parameter and entering the port number.
Another thing you could do would be a simple traceroute.
Test-NetConnection thomasmaurer.ch -TraceRoute
If you want to do a ping -t you could use the following command
while ($true) {Test-NetConnection -InformationLevel Quiet}
I hope this helps you a little
Find more networking PowerShell cmdlets in my PowerShell Networking cheatsheet.
Tags: Microsoft, Networking, Ping, port, Portscan, PowerShell, Test-NetConnection, Traceroute, Windows, Windows Server Last modified: June 29, 2020
About the Author / Thomas Maurer
Thomas works as a Principal Program Manager & Chief Evangelist Azure Hybrid at Microsoft (Cloud + AI). He engages with the community and customers around the world to share his knowledge and collect feedback to improve the Azure hybrid cloud and edge platform. Prior to joining the Azure engineering team (Cloud + AI), Thomas was a Lead Architect and Microsoft MVP, to help architect, implement and promote Microsoft cloud technology.
If you want to know more about Thomas, check out his blog: www.thomasmaurer.ch and Twitter: www.twitter.com/thomasmaurer
Ранее я писал о том Где telnet в Windows 7 / 8 / 8.1, статья рассказывала как включить компонет telnet в Windows 7 и выше. Но как правило в большинстве случаев Telnet используется для диагностики сети, а именно проверить открыт ли порт. Собственно в последних версиях PowerShell для диагностики сети Telnet то и не нужен. Есть замечательный командлет Test-NetConnection, в результе выполнения которого в выводе будет информация о том доступен ли сервис по ICMP и в том числе по указанному порту.
Все очень просто, запускаем PowerShell и выполняем команду Test-NetConnection
Если выполнять команду без параметров, то это будет просто проверка на наличие Интернет соединения.
Но в моем примере будет все просто, я проверю доступность своего сайта по 443 порту (HTTPS)
Вот она простая и детальная информация о доступности соединения.
The `Test-NetConnection` cmdlet in PowerShell is used to diagnose network connectivity issues by testing connections to a specified computer or port.
Test-NetConnection -ComputerName "example.com" -Port 80
Test-NetConnection is a robust PowerShell cmdlet designed for testing network connectivity. It serves multiple purposes, and understanding its functionality can greatly assist IT professionals in diagnosing network issues. This tool can test whether a specific port on a remote computer is reachable, check IP configuration, and provide diagnostic information about the networking stack.
In comparison to other networking commands such as Ping and Tracert, Test-NetConnection offers more detailed information about network status and can check port-specific connectivity, making it a versatile choice for network diagnostics.
PowerShell Test SQL Connection Made Easy
Basic Syntax of Test-NetConnection
The basic syntax of Test-NetConnection is straightforward and can be customized with various parameters to suit specific needs. Here’s a simple format of the command:
Test-NetConnection -ComputerName [hostname or IP]
For instance, if you want to check connectivity to Google, you would use:
Test-NetConnection -ComputerName google.com
This command provides essential outputs to help you understand the network conditions to the specified remote host.
Mastering PowerShell Selection: Quick Tips and Techniques
Key Features of Test-NetConnection
Testing Connectivity to a Host
One of the primary functions of Test-NetConnection is to check basic connectivity to a remote host. Below is an example of using Test-NetConnection to verify if you can reach a well-known website:
Test-NetConnection -ComputerName google.com
This command will return information including whether the host is reachable and the round-trip time for packets sent to the site.
Checking Specific Port Connectivity
In many cases, you may want to test connectivity to a specific service running on a host. This is particularly useful for web servers or database connections. You can specify ports using the -Port parameter.
For example, to test connectivity to a web server on port 80, use:
Test-NetConnection -ComputerName example.com -Port 80
This command checks if the HTTP service on port 80 is accessible.
Testing with Additional Parameters
The functionality of Test-NetConnection can be enhanced with various additional parameters like -InformationLevel and -TraceRoute.
For instance, the following command provides detailed information about the connection:
Test-NetConnection -ComputerName example.com -Port 80 -InformationLevel Detailed
This allows for greater insight into exactly what is happening in the network layer and helps to diagnose specific problems.
Mastering PowerShell Get-Credential: A Quick Guide
Advanced Usage of Test-NetConnection
Using Test-NetConnection for Traceroute
Test-NetConnection can also serve as a traceroute tool, helping to identify the path that packets take to reach a destination, along with any potential bottlenecks or losses:
Test-NetConnection -ComputerName example.com -TraceRoute
This is vital for network troubleshooting and can highlight issues along the route to the destination.
Testing IPv6 Connectivity
With the increasing adoption of IPv6, it is essential to ensure that your network is functioning correctly in this newer format. The Test-NetConnection cmdlet can help you perform tests on IPv6 connectivity:
Test-NetConnection -ComputerName ipv6.google.com -Port 80 -AddressFamily IPv6
This command assesses whether port 80 on Google’s IPv6 address is reachable, which is critical for modern network applications.
Mastering PowerShell Transcription: A Quick Guide
Interpreting Test-NetConnection Results
Understanding the results returned by Test-NetConnection is key to effective network diagnostics. The output typically includes several key pieces of information:
- ComputerName: The target you’re testing.
- RemoteAddress: The IP address that resolves for the specified hostname.
- RemotePort: The port being tested.
- PingSucceeded: Indicates if a ping to the target was successful.
- TcpTestSucceeded: Indicates if the TCP connection to the specified port was successful.
For example, after running the command, you might see output similar to:
ComputerName : google.com
RemoteAddress : 142.250.190.78
RemotePort : 80
InterfaceAlias : Ethernet
SourceAddress : 192.168.1.5
PingSucceeded : True
PingReplyDetails (RTT): 12 ms
TcpTestSucceeded : True
In this output, you can see that both the ping and TCP test to the specified port were successful. Each section helps you to determine the state of your network connections.
Mastering PowerShell Connect-MsGraph in Simple Steps
Common Troubleshooting Scenarios
Issues Detected by Test-NetConnection
Test-NetConnection is invaluable when troubleshooting connectivity issues. It might uncover common problems such as:
- Firewall Settings: If a connection doesn’t succeed, it could be due to firewall rules blocking access to certain ports.
- Service Availability: If the port is not open, the service you’re trying to reach may be down.
Understanding the output helps diagnose and rectify these issues effectively.
Using Test-NetConnection in Scripts
To further enhance productivity, you can automate connectivity tests through scripting. For example, you might want to check connectivity to multiple servers in a loop:
$servers = "example.com", "testserver123"
foreach ($server in $servers) {
Test-NetConnection -ComputerName $server -Port 80
}
This script iterates over a list of servers, checking each one for connectivity on port 80, allowing you to quickly assess the status of multiple connections.
Mastering PowerShell Connect-AzAccount in Minutes
Best Practices for Using Test-NetConnection
- Regularly test critical connections to ensure they remain stable.
- Utilize Test-NetConnection as a preliminary diagnostic tool before diving deeper into network analysis.
- Document your findings to build a knowledge base for troubleshooting.
Mastering PowerShell Get-ADObject: A Quick Guide
Conclusion
In summary, Test-NetConnection is an essential tool for network professionals seeking to ensure reliable connectivity in their environments. By mastering its use and exploring the different parameters, you can enhance your troubleshooting capabilities and maintain a well-functioning network. Dive deeper into PowerShell commands and expand your skills further with advanced networking techniques!
Mastering PowerShell Garbage Collection with Ease
Resources
For further reading and exploration:
- Official PowerShell Documentation on Test-NetConnection.
- Advanced PowerShell Networking Articles for deeper insights.
- Consider enrolling in specialized PowerShell courses to strengthen your understanding of the scripting language.
Mastering PowerShell Naming Convention: A Quick Guide
FAQs
What is the difference between Test-NetConnection and Ping?
While both commands test connectivity, Test-NetConnection provides more detailed information about the connection status and can check for specific port accessibility.
Can Test-NetConnection be used on non-Windows systems?
No, Test-NetConnection is a PowerShell cmdlet and is limited to Windows environments. However, similar functionality can often be achieved with other command-line tools on different operating systems.
How can I integrate Test-NetConnection into my network monitoring tools?
You can easily script it and schedule regular checks using Windows Task Scheduler or integrate it within larger PowerShell scripts that are part of your network monitoring routines.