В 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
Test-NetConnection – a fix-to-employ cmdlet to check network connection has appeared in PowerShell 4.0 (Windows 2012 R2, Windows 8.i and newer). You can utilize this cmdlet to check the response and availability of a remote server or network service on it, TCP ports blocked by firewalls, check ICMP availability and routing. In fact, the Examination-NetConnection
cmdlet can supervene upon several standard network admin tools at once: ping, traceroute, TCP port scanner, etc.
Contents:
- Testing for Open up/Airtight Server TCP Ports with Test-NetConnection
- Test-NetConnection in PowerShell Monitoring Scripts
- Simple IP Network / Port Scanner with PowerShell
From time to fourth dimension, any administrator has to check service availability on a remote server by checking remote TCP port response (for example, the availability of an email or web server). Moreover, most admins are used to perform such a port check with the telnet
command. For instance, to make sure the SMTP service responds on the e-mail server (by default, it responds on TCP Port 25) information technology is enough to run telnet ny-msg01.woshub.com 25
command. But starting from Windows 7, the telnet client has become a feature to be installed separately. Let’due south see how to bank check for open/closed TCP ports using PowerShell.
The master do good of the Test-NetConnection
cmdlet is that it is already a part of all modern versions of Windows and y’all don’t need to install it separately. The cmdlet is a part of the NetTCPIP module (starting with PoSh v4.0).
Tip. You can check the current installed version of PowerShell with the command: $PSVersionTable.PSVersion
Value 4 in the Major column means that PowerShell 4.0 is installed on your computer.
Testing for Open/Airtight Server TCP Ports with Test-NetConnection
Let’south check if TCP Port 25 (SMTP protocol) is open up (available) on the remote email server using Test-NetConnection:
Test-NetConnection -ComputerName ny-msg01 -Port 25
Note. Using Examination-NetConnection cmdlet, you can check only TCP port connexion, and information technology is not applicable to bank check the availability of the remote UDP ports.
The shortened version of the aforementioned command looks like this: TNC ny-msg01 -Port 25
Permit’southward consider the result of the command:
ComputerName : ny-msg01 RemoteAddress : ten.20.1.7 RemotePort : 25 InterfaceAlias : CORP SourceAddress : 10.20.1.79 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : True
As y’all tin see, the cmdlet resolves the server name to IP address, checks the ICMP response (similar to ping) and the availability of the TCP port. The specified server responds via ICMP (PingSucceeded = Truthful
) and the TCP Port 25 is open (RemotePort=25, TcpTestSucceeded= True
).
Notation. In some cases, it may occur that PingSucceeded=False, and TcpTestSucceeded=True. Information technology is likely to hateful that ICMP Ping is forbidden on the remote server.
The cmdlet has a special parameter –CommonTCPPort, which allows you to specify the name of a known network protocol (HTTP, RDP, SMB, WINRM).
For example, to cheque the availability of an HTTP web server, you can use the command:
Test-NetConnection -ComputerName woshub.com -CommonTCPPort HTTP
Or RDP port (3389) availability:
Test-NetConnection ny-rds1 –CommonTCPPort RDP
You can list all the parameters that the Exam-NetConnection cmdlet returns:
Examination-NetConnection ny-man01 -port 445|Format-List *
If y’all only demand to see if the port is available, it tin can be checked more quickly:
TNC ny-msg1 -Port 25 -InformationLevel Placidity
The cmdlet returned True
, which means the remote port is attainable.
Tip . In before PowerShell versions, you could check TCP port availability as follows:
(New-Object Organization.Cyberspace.Sockets.TcpClient).Connect('ny-msg01', 25)
In Windows 10 / Windows Server 2016, you can utilise the Test-NetConnection cmdlet to trace the route to a remote server using the –TraceRoute parameter (analogous to tracert control in Windows). Using the –Hops parameter, you lot tin can limit the maximum number of hopes during route cheque.
Test-NetConnection ny-man01 –TraceRoute
The cmdlet returned the network summary filibuster when accessing the server in milliseconds (PingReplyDetails (RTT): 41 ms
) and all the IP addresses of the routers on the way to the target server.
Test-NetConnection in PowerShell Monitoring Scripts
The following command allows y’all to check the availability of a specific port on a number of servers, the list of which is stored in a plain text file list_servers.txt. We need the servers where the specified service doesn’t respond:
Get-Content c:\PS\list_servers.txt | where { -Non (Test-Netconnection $_ -Port 25 -InformationLevel Quiet)}| Format-Table -AutoSize
Similarly, you tin can create a unproblematic monitoring script that checks the availability of servers and displays a notification if one of the servers is unavailable.
For example, you can cheque the availability of basic services on all domain controllers (a DC list tin be obtained with the Get-ADDomainController cmdlet). Allow’s check the following services on DC (the PortQry tool has a similar «Domain and trusts» dominion):
- 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", "eighty", "443"
$AllDCs = Go-ADDomainController -Filter * | Select-Object Hostname,Ipv4address,isGlobalCatalog,Site,Woods,OperatingSystem
ForEach($DC in $AllDCs)
{
Foreach ($P in $Ports){
$check=Examination-NetConnection $DC -Port $P -WarningAction SilentlyContinue
If ($check.tcpTestSucceeded -eq $true)
{Write-Host $DC.proper name $P -ForegroundColor Green -Separator " => "}
else
{Write-Host $DC.name $P -Separator " => " -ForegroundColor Reddish}
}
The script volition check the specified TCP ports on the domain controllers, and if one of the ports is unavailable, it will highlight it in red (yous can run this PowerShell script as a Windows service).
Simple IP Network / Port Scanner with PowerShell
You tin can also implement a simple port and IP subnet network scanner to scan remote servers or subnets for open up/airtight TCP ports.
Scan the range of IP addresses on open port 3389:
foreach ($ip in 100..150) {Examination-NetConnection -Port 3389 -InformationLevel "Detailed" 192.168.one.$ip}
Scan the range of TCP ports from 1 to 1024 on the specified remote server:
foreach ($port in 1..1024) {If (($a=Test-NetConnection srvfs01 -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open up!"}}
The Test-NetConnection Powershell cmdlet can be used to test ports on remote hosts which is great for firewall Troubleshooting but for for older operating systems an alternative can be used.
For 2008 the following Powershell cmdlet can be used (new-object system.net.sockets.tcpclient).connect(“IP”,”PORT”)
Related Post
This post contains a demo for how to check if a port is open using PowerShell, whether you are on the latest or older versions of Windows.
All admins need to know how to test connectivity to remote server ports. In fact, all software developers and other technical folks do too in my opinion!
If one server needs to connect to another, we need network line of sight, meaning we need to ensure the network traffic can flow from one place to another. Generally applications connect using specific ports, and to check if the network is good you’d run a network test using an IP (or servername) including the port number.
On Windows, Putty is commonly used to test network ports, however PowerShell provides a much easier alternative which I demo in this post. The two methods for testing network connectivity on specific ports are from a Microsoft DBA’s perspective, so you’ll see RDMS related ports here!
Topics Covered:
1. How to Check a Port is Open (Test-NetConnection)
2. How to Check a Port is Open (Pre Windows Server 2012)
3. Further Troubleshooting Network Issues
Important ports to remember in the life of a DBA might include:
> SQL Server (1433, 1434 & 5022)
> RedShift (5439)
> PostgreSQL (5432)
> MySQL (3306)
> Oracle (1521)
1. How to Check a Port is Open (Test-NetConnection)
The best way for checking if a port is open on Windows is by using the Test-NetConnection cmdlet. I use this very often, and have done for years. It’s built-in to recent versions of PowerShell, and its easy to use/remember.
To test if network flow on a port is open between severs on Windows, we can run the following:
# Test remote port is open Test-NetConnection -ComputerName lab-sql1.whyte.net -Port 1433 # Same as above command using alternative syntax/ip tnc 172.31.18.100 -port 1433
When you run this command and it hangs for 60 seconds, that will generally mean it’s going to fail. If the TcpTestSucceeded
output returns false
, that means the network port test has failed.
Note: Network traffic may pass through firewalls, NAT gateways, security groups, or load balancers. If issues persist, cross-check with PuTTY and review firewall/network logs. You might need to contact your network team and raise an ACL request to open this network flow, or DevOps if the Cloud Infra side needs opened.
2. How to Check if a Port is Open (Pre Windows 2012)
The PowerShell script below is useful for when you’re running on legacy Windows versions (pre-Windows Server 2012).
I’ve spawned a Windows Server 2008 R2 Server for this demo to verify. The PowerShell script below will help you check if a port is open on older Windows versions:
# Check a port is open (pre Win08/Svr2012) $Ipaddress= Read-Host "Enter the IP address:" $Port= Read-host "Enter the port number to access:" $t = New-Object Net.Sockets.TcpClient $t.Connect($Ipaddress,$Port) if($t.Connected) {"Port $Port is operational."} else {"Port $Port is closed."}
Below is an example of no connectivity, it’s failing to connect on port 1433. The server I’m testing does not have SQL Server installed, so there was nothing listening on that port.
3. Further Troubleshooting Network Issues
If connectivity fails, consider the following checks:
– Server Listening: Ensure there is a service actively ‘listening’ on the remote server port.
– Network Configurations: Verify DNS settings, network configurations, and Security Groups.
– Firewalls: Check both infrastructure-level and local host firewalls for potential restrictions.
Note: Diagnosing complex connectivity issues may involve various components, including firewalls, NAT Gateways, and load balancers. While this test is straightforward, for thorough troubleshooting, consider running additional tests with tools like PuTTY.
Ever since telnet client is not enabled by default in Windows Server 2008(also in 2012 and 2016), SysAdmins has tough time using telnet command when they need it. In this post, let us see what are the options for us to telnet without using actual telnet.exe
We have two options when there is no telnet.exe command.
- Using .Net classes to perform the telnet
- Using Test-NetConnection cmdlet (available from Windows Server 2012 onward)
Using .Net Classes to perform the telnet
The System.Net.Sockets.TCPClient class provides facility to perform telnet operation to remote host on specified port. I have posted about this in past with the title Test Port Connectivity using PowerShell. This article has a function which you can import into your shell and use it to perform the telnet operation.
This method works for all versions of windows operating systems as it is using underlying .Net Module.
Using Test-NetConnection cmdlet
Starting Windows Server 2012, Microsoft has provided a inbuilt function for this purpose. It is called Test-NetConnection. This function can be used to perform telnet, traceroute and many other operations. In this post I will limit the discussion to telnet functionality.
To telnet to a port on remote computer you have to use –ComputerName and –Port parameters of this function. For example, if you want to check if google.com is responding on port 80, then use below command.
Test-NetConnection -ComputerName google.com -Port 80
After completing the execution, it returns an object which will tell you the output of the telnet. The TCPTestSucceeded value will be True if the telnet is successful and will be False if the telnet has failed.
Look at the below screenshots for understanding this.
Telnet Successful:
Telnet Failure:
As mentioned before this works on Windows Server 2012 or above only. If you need same thing for previous versions you need to use the first approach that I mentioned.
Hope this helps.