Testing Server Connectivity with Netcat

How many times have we been asked to troubleshoot a server connectivity problem?
Sooner or later, you end up in a three way call between yourself, the firewall folks,
and the admin of the server on the other end, so that everyone can snoop/filter or
otherwise capture an attempted connection. Unfortunately, getting that three way
call going can be difficult, especially when the folks required are not readily available.

Wouldn’t it be nice, if you could just set something up to try the connection over and
over, so that you don’t have to type “telnet {ip} {port}” yourself a million times ?

That’s where netcat (a.k.a nc) comes into play… Available pre-compiled from
Sunfreeware – this little tool will save you some time. The following shell script will
call on netcat to try the connection once a minute until  it is successful.
Then it will send an email, and be done.

#!/bin/ksh

HOST=1.2.3.4; PORT=567
NOTIFY=someone@somewhere.com
WAIT_TIME=5; SLEEP_TIME=55

DONE=1
while [ ${DONE} -gt 0 ]
do
   /local/bin/nc -z -w ${WAIT_TIME} ${HOST} ${PORT}
   DONE=$?
   [ ${DONE} -gt 0 ] && sleep ${SLEEP_TIME}
done

mailx -s "Connection to Host ${HOST} Port ${PORT} succeeded." ${NOTIFY} < /dev/null

You could easily extend the functionality of this… Let’s say you have to maintenance
window where you shut down your application for a while because the database it talks
to in  the back end is unavailable… This script could easily “listen” for that database
to be available again, and instead of sending you an email at the end, it could be triggered
to start up your application.

Give it a try.