Pages

Use PowerShell To Test Port

There are times when we need to identify or troubleshoot if firewall exception is configured correctly and the desired remote server port is open. Often time, I have seen IT Professional use Telnet or PuTTY to test. However, there is another way to do it with PowerShell.

By default, Telnet is not installed on Windows or Windows Server. In order to use Telnet, the Telnet client has to be installed. In Windows, this can be done through Control Panel > Programs and Features > Turn Windows features on or off, and check the Telnet Client. For Windows Server, go to Server Manager > Features > Add Features > Telnet Client.

Or add the Telnet Client feature through PowerShell,
Import-Module ServerManager
Add-WindowsFeature -Name Telnet-Client
Instead of installing the Telnet client, alternatively we could use Windows Sockets through the System.Net.Sockets provided in .NET framework.

To test TCP port,
$tcp = New-Object System.Net.Sockets.TcpClient
$tcp.connect('<remote server>', <port>)
Or even one line of code if you wish,
(New-Object System.Net.Sockets.TcpClient).Connect('<remote server>', <port>)
That's it! No additional installation (provided that PowerShell is installed, of course).

Starting in Windows Server 2012 R2, Microsoft includes Test-NetConnection in NetTCPIP Module. This command could be used to simulate the traditional ping, tracert, and testing TCP connectivity.
# ping
Test-NetConnection -ComputerName <remote server>

# tcp test on a port
Test-NetConnection -ComputerName <remote server> -Port <port>

# tracert
Test-NetConnection -ComputerName <remote server> -TraceRoute
A note on UDP port testing. UDPClient.connect only specify the host/port to that UDP client without actually connecting the remote host. Since UDP uses connectionless transmission which is hard to reliably determining if a remote UDP port is open/close. it seems like one way to test is to send some packets to the remote UDP port and if "ICMP port unreachable" is received back, the UDP port is considered as close. Otherwise, it is unknown.

No comments:

Post a Comment