В 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
In PowerShell, you can use the Test-NetConnection cmdlet to check whether a port is available (open) on a remote computer. You can use this cmdlet to check the response and availability of a remote server or a network service, test whether the TCP port is blocked by a firewall, check ICMP availability, and routing. In fact, Test-NetConnection
replaces several popular network admin tools such as ping
, tracert
, telnet
, pathping
, TCP port scanner, etc.
Contents:
- Check for Open TCP Port with Test-NetConnection
- PowerShell: Check for Open Ports on Multiple Hosts
- Simple TCP/IP Port Scanner in PowerShell
- How to List Open Ports on Windows with PowerShell
Check for Open TCP Port with Test-NetConnection
You can use the Test-NetConnection cmdlet to check only TCP ports. For example, to check that TCP port 25 (the SMTP protocol) is open on the remote mail server:
Test-NetConnection -ComputerName ny-msg01 -Port 25
Note. You can test only a TCP port connectivity by using the Test-NetConnection cmdlet. However, you cannot use the cmdlet to check the availability of the remote UDP ports.
The Test-NetConnection command has the alias TNC. The shortened version of the same command looks like this:
TNC ny-msg01 -Port 25
Let’s look at the result of the command:
ComputerName : ny-msg01 RemoteAddress : 10.20.1.7 RemotePort : 25 InterfaceAlias : CORP SourceAddress : 10.20.1.79 PingSucceeded : True PingReplyDetails (RTT) : 0 ms TcpTestSucceeded : True
As you can see, the cmdlet resolves the server name to an IP address, checks the ICMP response (similar to ping
), and checks the response from the TCP port (port availability). The specified server responds via ICMP (PingSucceeded = True
) and the TCP Port 25 is open (RemotePort=25, TcpTestSucceeded= True
).
Note. If the command returns PingSucceeded=False and TcpTestSucceeded= True, this most likely means that the ICMP Echo request (ping) is disabled on the remote computer.
If you run the Test-NetConnection without parameters, it will check if the computer is connected to the Internet (checks for the availability of the internetbeacon.msedge.net
host).
You can add the –InformationLevel Detailed option to display detailed information when checking a remote TCP port:
TNC 192.168.32.101 -Port 3389 -InformationLevel Detailed
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 check the availability of an HTTP web server you can use the command:
Test-NetConnection -ComputerName woshub.com -CommonTCPPort HTTP
Or check the availability of a default RDP port (TCP/3389):
Test-NetConnection ny-rds1 –CommonTCPPort RDP
You can list all of the parameters that the Test-NetConnection cmdlet returns:
Test-NetConnection ny-man01 -port 445|Format-List *
If you only need to see if the port is available, it can be checked more quickly:
TNC ny-msg1 -Port 25 -InformationLevel Quiet
The cmdlet returns True
, which means that the remote TCP port is open.
Tip. In earlier versions of Windows PowerShell (before version 4.0), you could check the availability of a remote TCP port with the command:
(New-Object System.Net.Sockets.TcpClient).Connect('ny-msg01', 25)
You can use the Test-NetConnection cmdlet to trace a route to a remote server by using the –TraceRoute parameter (similar to the built-in tracert
command in Windows). You can limit the maximum number of hops during the route check by using the -Hops parameter.
Test-NetConnection ny-man01 –TraceRoute
Cmdlet returned a summary network access delay in milliseconds (PingReplyDetails (RTT): 41 ms
) as well as all the IP addresses of the routers on the way to the destination host.
PowerShell: Check for Open Ports on Multiple Hosts
You can use PowerShell to check for the availability of a specific port on a number of remote computers. Save the list of hostnames or IP addresses in a plain text file with the name servers.txt
.
For example, your task is to find hosts where the TCP/25 port is not responding or is closed on a list of servers:
Get-Content c:\PS\list_servers.txt | where { -NOT (Test-Netconnection $_ -Port 25 -InformationLevel Quiet)}| Format-Table -AutoSize
You can use a simple monitoring PowerShell script that checks the availability of remote servers and displays a pop-up notification if any of the servers are unavailable.
For example, you can check the availability of basic services on all domain controllers during an AD health check (a DC list can be obtained with the Get-ADDomainController cmdlet). Let’s check the following services on the DC (there is a similar ‘Domain and trusts‘ rule in the PortQry tool):
- 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}
}
}
The script checks the specified TCP ports on the domain controllers, and if any of the ports are unavailable, it highlights them in red (you can run this PowerShell script as a Windows service).
Simple TCP/IP Port Scanner in PowerShell
You can use PowerShell to implement a simple IP scanner that scans remote hosts or IP subnets for open/closed TCP ports.
To scan the range of IP addresses between 192.168.1.100 and 192.168.1.150 and display computers that have port 3389 open:
foreach ($ip in 100..150) {Test-NetConnection -Port 3389 -InformationLevel "Detailed" 192.168.1.$ip}
Scan a range of TCP ports (from 1 to 1024) on a remote host:
foreach ($port in 1..1024) {If (($a=Test-NetConnection srvfs01 -Port $port -WarningAction SilentlyContinue).tcpTestSucceeded -eq $true){ "TCP port $port is open!"}}
How to List Open Ports on Windows with PowerShell
Use the Get-NetTCPConnection cmdlet to list the ports that are open on the local computer (this is the PowerShell equivalent of NETSTAT
). A list of all open TCP ports on the computer can be viewed as follows:
Get-NetTcpConnection -State Listen | Select-Object LocalAddress,LocalPort| Sort-Object -Property LocalPort | Format-Table
If you want to find out which program (process) is listening on a specific port on your computer, use the following command (where 443 is a port number you want to check):
Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess | ft Id, ProcessName, UserName, Path
In PowerShell, you can test the connectivity of a TCP port using the `Test-NetConnection` cmdlet to check if a specific host is reachable on a given port.
Test-NetConnection -ComputerName "example.com" -Port 80
Understanding PowerShell and TCP Ports
TCP (Transmission Control Protocol) is one of the core protocols of the Internet Protocol Suite. It enables reliable communication between devices over a network by establishing connections that ensure data is transmitted without errors.
Ports are numerical identifiers in TCP that facilitate the routing of network traffic. Each application running on a device typically communicates over a specific port, making it crucial to test these ports when troubleshooting network issues or configuring servers.
PowerShell is a powerful command-line interface and scripting language that allows administrators to automate tasks and manage systems effectively. One of its many capabilities includes testing the connectivity of TCP ports.
PowerShell Test UDP Port: A Step-by-Step Guide
Introduction to PowerShell Port Testing
Testing port connectivity is essential for various reasons, including ensuring that applications can communicate with each other, verifying firewall configurations, and troubleshooting issues related to network connectivity. Understanding how to effectively use PowerShell for these tasks can significantly streamline your administrative duties, making it a valuable skill for any IT professional.
Exploring PowerShell Test-Path for Quick File Checks
PowerShell Commands for Port Testing
The `Test-NetConnection` Command
The `Test-NetConnection` cmdlet is one of the most versatile tools available in PowerShell for testing TCP connectivity. This command can check if a specific port on a remote server is open and accessible.
Syntax:
Test-NetConnection -ComputerName <hostname|IP> -Port <portnumber>
Example Usage:
To test whether port 80 (typically used for HTTP) is open on a website:
Test-NetConnection -ComputerName "example.com" -Port 80
The output will indicate whether the port is open, along with additional information about the connection.
The `Test-Connection` Command
While `Test-NetConnection` is specifically designed for testing TCP connectivity, the `Test-Connection` cmdlet is primarily used for checking ICMP (ping) connectivity.
Example Usage:
To check the connectivity without specifying the port, you would use:
Test-Connection -ComputerName "example.com"
This will return whether the host is reachable but does not provide information about specific ports.
The `tnc` Alias
PowerShell provides an alias, `tnc`, for the `Test-NetConnection` cmdlet to simplify the command-line syntax.
Example Usage:
Testing port 80 using the alias is as straightforward as:
tnc "example.com" -Port 80
This command behaves similarly to `Test-NetConnection` but is quicker to type as part of your daily tasks.
Checking Port Status
Detecting Open Ports
Identifying open ports is crucial for verifying that services are running as expected. When a port is open, it signifies that the application associated with it is listening for connections.
Example Command:
To check if port 443 (HTTPS) is open:
Test-NetConnection -ComputerName "example.com" -Port 443
Checking for Closed or Filtered Ports
If a port is closed or filtered, the output will provide this information, indicating a possible issue with the server or network configuration.
Example Command:
To test if port 25 (SMTP) is open or closed, use:
Test-NetConnection -ComputerName "example.com" -Port 25
The results will tell you if the connection was successful or not, providing context for troubleshooting.
PowerShell Test-NetConnection: A Quick Guide to Connectivity
Advanced TCP Port Testing Techniques
Using `Test-NetConnection` with Additional Parameters
`Test-NetConnection` offers a variety of parameters beyond just the computer name and port.
Example:
Getting a more detailed output when testing a connection can be accomplished with:
Test-NetConnection -ComputerName "example.com" -Port 80 -InformationLevel Detailed
This will provide extensive details about the connection attempt, including the underlying network conditions.
Diagnosing from Remote Locations
Sometimes, you may need to check ports across different remote servers. PowerShell Remoting is your friend here, allowing you to run commands on remote systems.
Example:
To check port connectivity from a remote server:
Invoke-Command -ComputerName "RemoteServer" -ScriptBlock { Test-NetConnection -ComputerName "example.com" -Port 80 }
This command will execute the port test on the specified remote server.
Mastering PowerShell: How to Stop a Process Effortlessly
Practical Applications
Troubleshooting Common Networking Issues
PowerShell commands for port testing can play a crucial role in diagnosing various connectivity issues. For instance, if a web application is not functioning properly, a quick check of the relevant TCP ports can determine if the required services are up and running.
Port Testing in Automation Scripts
You can integrate these commands into your automation scripts to regularly monitor the status of key services. This proactive approach ensures you catch issues early on.
Example Script Snippet:
Here’s how you could test multiple servers to check port 80:
$servers = @("server1", "server2", "server3")
foreach ($server in $servers) {
tnc $server -Port 80
}
This script iterates through a list of servers and checks the specified port, providing ongoing visibility into server health.
Powershell Get Certificate: A Quick Guide to Mastery
Conclusion
In summary, understanding how to effectively utilize PowerShell to test TCP ports empowers you to troubleshoot connectivity issues and ensure that your applications and services are accessible as intended. The commands discussed, including `Test-NetConnection`, `Test-Connection`, and the `tnc` alias, equip you with the tools needed for robust network management.
PowerShell List Certificates: A Quick Guide
Additional Resources
For those looking to deepen their understanding of network diagnostics in PowerShell, consult the official Microsoft documentation or consider additional training materials dedicated to PowerShell scripting and networking functions.
PowerShell Restart Process: Simple Steps to Master It
FAQs
What is the difference between `Test-NetConnection` and `Test-Connection`?
`Test-NetConnection` is specialized for testing TCP connections to specific ports, while `Test-Connection` is optimized for pinging hosts using ICMP packets.
Can I test multiple ports at once with PowerShell?
You can run a loop to check multiple ports or integrate it into an automated script to check an array of ports across different hosts.
What will the output of the `Test-NetConnection` command look like?
The output includes the result of the connection attempt, the IP address resolved, and additional information about the network path.
Are there any limitations to using PowerShell for port testing?
While PowerShell is powerful, port testing can be affected by firewall settings, network restrictions, or insufficient permissions on the targeted servers, which might limit your ability to gather accurate results.
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.
During troubleshooting of different issues it is often required to check if some TCP port on a remote host is opened and ensure that it is not blocked by a firewall.
The most common tool for this is telnet
, but it may not be installed or you may want to be able to copy the output to paste it into a ticket or to send it someone, that is not always possible with telnet
.
Also the telnet
command is not very handy if you need to check connectivity to multiple hosts/ports, but you can do this easily with a PowerShell.
In Windows, you can test connection to TCP port from the command line using PowerShell and in this note i will show how to do this.
Cool Tip: How to install telnet
in Windows! Read more →
Use one of the following PowerShell commands to check if TCP port on a remote host is opened:
PS C:\> tnc www.shellhacks.com -Port 443
– or –
PS C:\> New-Object System.Net.Sockets.TcpClient("www.shellhacks.com", 443)
Check open ports on multiple hosts
If you need to test multiple TCP connections, list the required destinations and copy/paste the script into the PowerShell console:
PS C:\> @" # List of hosts and ports to check www.shellhacks.com:443 8.8.8.8:53 8.8.4.4:53 "@.split("`n") | ForEach-Object { $server,$port = $_.split(':') echo "Host: $_" New-Object System.Net.Sockets.TcpClient("$server", $port) | Out-String -Stream | Select-String "Connected" }
Was it useful? Share this post with the world!