Tuesday 8 May 2012

Use PowerShell to test TCP and UDP connectivity (Open TCP/UDP Socket)

A while ago some security expert, and I use expert in the loosest sense of the word, raised the alarm about telnet. Yes, that old trusted telnet used by all to test connectivity using TCP sockets and used by none, I hope, to connect to a remote shell. If you are reading this and still use telnet to connect to a remote shell, let me introduce you to openSSH.

Telnet, we were told was not secure, which is true, but it is also true that not a single server in the estate had a telnet server running. All (windows) servers could use a telnet client, but it's not very useful if the server is not there, but no matter a new GPO was created to prevent the use of the telnet client.

Today, we needed to test connectivity to a server as a batch had failed. We were being told that it was a network issue and thus we needed to be able to establish that this was not the case, but telnet was not available, thank you security expert, which raised a bit of an issue. Enter PowerShell:
 $socket = New-Object net.sockets.tcpclient("hostname",portnumber)
That is it. If the socket can be opened this will take a very short time, if it can't then, it will take a while to time out. Note that the IP address can be used instead of the hostname, but the method still takes a string, so it must be in quotes:
PS C:\> $socket =New-Object net.sockets.tcpclient("74.125.132.105",80)
PS C:\> $socket

Client              : System.Net.Sockets.Socket
Available           : 0
Connected           : True
ExclusiveAddressUse : False
ReceiveBufferSize   : 8192
SendBufferSize      : 64512
ReceiveTimeout      : 0
SendTimeout         : 0
LingerState         : System.Net.Sockets.LingerOption
NoDelay             : False
Note, that there is a udpclient on the System.Net.Sockets namespace that can be used for testing udp connectivity.

For completeness, this is the result of trying to connect on port 8210:
PS C:\> $socket =New-Object net.sockets.tcpclient("74.125.132.105",8210)
New-Object : Exception calling ".ctor" with "2" argument(s): "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.132.105:8210"
At line:1 char:20
+ $socket =New-Object <<<<  net.sockets.tcpclient("74.125.132.105",8210)
 + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
 +FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

PS C:\> $socket

Client              : System.Net.Sockets.Socket
Available           : 0
Ttl                 : 32
DontFragment        : False
MulticastLoopback   : True
EnableBroadcast     : False
ExclusiveAddressUse : False

No comments:

Post a Comment