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 →
Test Connection to Port using PowerShell
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" }
Also u can use
tnc
command in Windows 10 PowerShell:Thanks. Added to the article.
What is the variable to check programmatically afterwards?
$? seems to be always True
The output of tnc HOST_NAME -port PORT_NUMBER by default exports an object with several items. I think what you’re looking for is $_.TcpTestSucceeded
I think it would be appropriate to say what ‘tnc’ is (Test-NetConnection).
@”
http://www.shellhacks.com:443
104.143.84.13:443
“@.split(“`n”) | ForEach-Object {
$server,$port = $_.split(‘:’); write-host “serv: $server, port $port”
echo “Host: $_”
New-Object System.Net.Sockets.TcpClient(“$server”, $port) | Out-String -Stream | Select-String “Connected”
Test-NetConnection -ComputerName $server -Port $port | Out-String -Stream | Select-String “TcpTestSucceeded”
}
Why did you use quotes around $server?
Appreciate the various coding techniques/syntax to accomplish something – we learn more than just an answer to the problem.