В 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
Checking open TCP/IP ports on your Windows computer is crucial for managing network security and ensuring smooth connectivity. Certain apps and processes in Windows may face issues due to closed or misconfigured ports, often caused by firewalls or private IP addresses. This guide will walk you through step-by-step methods to check whether a TCP port is open or closed using built-in tools and third-party utilities.
Why You Should Check TCP/IP Ports?
Here are some common scenarios where checking ports is necessary:
- Troubleshooting connectivity issues for applications or services.
- Configuring firewalls to ensure necessary connections are allowed.
- Detecting suspicious activity that might indicate a security breach.
Methods to Check Open TCP/IP Ports
There are several ways to check open TCP/IP ports in Windows. Here are a few options:
Method 1. Using Telnet Client
Step 1: Check whether the telnet client feature is ON or not. In order to check, open the Turn Windows feature on or off settings from the search bar. OR press the ‘window’ key and type ‘windows’ features. Then press on “Turn Windows features on or off”.
Windows Features Option
A new prompt will be opened. Search for “Telnet Client” and check the box in front of ‘telnet Client’.
Windows Features
Step 2: Open the command prompt. Press the ‘windows’ key and type ‘cmd’. Press “Command Prompt”.
Command Prompt Option
Step 3: On the command prompt, type the command “telnet + IP address or hostname + port number” and check the status of the provided TCP port.
Telnet Command
Step 4: If only the blinking cursor is visible, then the port is open.
Port is Open
Step 5: If you get the message “connection failed” then the port is closed.
Port is close
Method 2: Using built-in netstat command-line utility:
Step 1: Open the command prompt.
Step 2: Run the following command:
netstat -an
Method 3. Using TcpView
Another option is to use the TcpView utility from Microsoft’s Sysinternals suite of tools. This utility provides a more user-friendly interface for viewing active TCP/IP connections, along with additional information such as the process ID and process name for each connection. Steps to be followed:
Step 1: Download the TcpView utility from the Microsoft Sysinternals website. You can find the download link on the TcpView page of the Sysinternals website.
Download Page
Step 2: Extract the downloaded file and run the TcpView.exe file to launch the TcpView utility. This will open the TcpView window, which shows a list of all active TCP/IP connections on your machine.
Extracted FIles
Step 3: Open the tcpview.exe (application).
By default, TcpView will display the following columns in the list of connections:
Protocol: Shows the protocol being used for the connection (TCP or UDP)
Local Address: Shows the local address and port being used for the connection
Remote Address: Shows the remote address and port being connected to
State: Shows the current state of the connection (e.g. Established, Listen, etc.)
You can use the “Local Address” and “Remote Address” columns to see which ports are being used by which applications. For example, if you see a connection with a local address of “127.0.0.1:80”, this means that the local application is using port 80 for outgoing connections.
Method 4. Using Windows PowerShell
You can also use Windows PowerShell to check open TCP/IP ports. To do this, use the Get-NetTCPConnection cmdlet, which allows you to view a list of active TCP/IP connections and the local and remote addresses and ports being used. For example, you can run the following command to view a list of all active TCP/IP connections:
Get-NetTCPConnection |
Select-Object LocalAddress,
LocalPort, RemoteAddress, RemotePort
Get-NetTCPConnection cmdlet
Method 5. Using Nmap
To install Nmap in the Windows command line, follow these steps:
Step 1: Download the latest version of Nmap from the Nmap website. You can find the download link on the Nmap download page:
https://nmap.org/download.html
Step 2: Extract the downloaded file to a location on your computer. This will create a new folder containing the Nmap files.
Step 3: Open a command prompt and navigate to the directory where you extracted the Nmap files. For example, if you extracted the files to the C:\nmap directory, you would run the following command:
cd C:\nmap
Step 4: Once you are in the Nmap directory, you can install Nmap by running the nmap.exe file. To do this, run the following command:
nmap.exe -V
This will display the version number of Nmap, indicating that it has been installed successfully.
Step 5: To use nmap to scan for open TCP/IP ports, run the “nmap -sT” command, followed by the IP address or hostname of the machine you want to scan.
nmap -sT localhost
This will scan the specified host or IP address and display the results. You can also use the -h option to view a list of available options and arguments for the nmap command. Overall, installing Nmap in the Windows command line is a straightforward process. You can download the latest version of Nmap from the Nmap website, extract the files, and then run the nmap.exe file to install it. Once it is installed, you can use the nmap command to scan hosts and IP addresses and view the results.
Common Issues That Close Ports
- Applications not functioning as expected.
- Misconfigured firewall rules blocking connections.
- IP addresses improperly set as private.
Troubleshooting Common Issues
Here are some common issues that may occur during opening TCP/IP Ports in Windows:
- Telnet Not Listed in Features: Ensure your system version supports Telnet or enable it via PowerShell.
- Firewall Blocking Ports: Temporarily disable the firewall to test port connectivity.
- Command Not Recognized: Verify tool installation and environment variables.
Conclusion
Checking open TCP/IP ports on your Windows computer is an important step for maintaining your system’s security and efficiency. By regularly monitoring these ports, you can identify any unwanted or suspicious connections that might put your computer at risk. Windows provides several simple tools, like Command Prompt and PowerShell, which make it easy to see which ports are open and what applications are using them. Taking the time to check your open ports helps ensure that your computer runs smoothly and stays protected from potential threats. Staying proactive about monitoring your network connections is a key part of keeping your digital environment safe and reliable.
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.