martes, 10 de julio de 2018

Ping to a specific port

Many times is necessary to check if a socket replies (a socket is the combination of a host and a port).
At least by my side, the most common way to do that is with the command telnet.
You only need to open a command prompt in Windows and type

telnet <ip address or hostname> <port>

But there are some problems with telnet:
  • Since Windows 7/2008, it is not installed by default, and maybe you have not rights to install it.
  • Each time you launch the command, the connection usually get stuck (it depends of the service we are testing) and you have to wait until the remote host cuts the connection.
There are a lot of third party software that we can use in Windows (netcat, nmap, etc). But in some cases you cannot use third party software in your computer because the security policy of your company forbids it.

Fortunately in PowerShell we can use the cmdlet Test-NetConnection for make some diagnostics for a network connection. It is a kind of PowerShell swiss army knife for networking, because it can replace the commands ping, telnet, and traceroute, and provides more info that these ones.

But in this case we can use this command (or his alias TNC) to check if a TCP port is open in a remote host. The syntax would be:

Test-NetConnection <ip address or hostname> -port <port>

The result of the test will be like this:

                              ComputerName           :
                              RemoteAddress          :
                              RemotePort             : 80
                              InterfaceAlias         : Ethernet 2
                              SourceAddress          :
                              PingSucceeded          : False
                              PingReplyDetails (RTT) : 0 ms
                              TcpTestSucceeded       : True

But really, this is not a ping, because it only makes a request, and sometimes we need a continuous connection attempt, per example when we are monitoring some remote service, and we have to launch the command each time we want to check the connectivity to the socket.
Well, why don't we use PowerShell to create a little tool to launch a ping to a specific port?
With only 4 lines of test, we have a tool that will ask us for the remote host and the remote port, and it will be probing the connection until we stop it. 

$destination_host = Read-host -prompt 'Input destination host'
$destination_port = Read-host -prompt 'Input destination port'

start-sleep -s 2
tnc $destination_host -port $destination_port | fl remoteaddress,RemotePort,tcptestsucceeded

} while ($destination_host=$destination_host)

Copy and paste the script in a notepad and save it as ping-port.ps1.
Then execute it in PowerShell and you have your new tool to check continuously a port in a remote host (to stop it, simply press Control+C).

No hay comentarios:

Publicar un comentario