Originally published May 13, 2018 @ 8:53 pm

There are several tools you can use to verify access to a remote network port: nc, tcping, telnet. Unfortunately, nc from the netcat package has been replaced by the one from nmap, which lacks the -z option, making it useless for non-interactive applications.

A partial workaround with nc is to use the timeout flags:

nc -v -i1 -w1 22

Unfortunately, this method lends itself poorly to automation as on occasion it tends to hang and needs to be ran with the timeout commands and that adds another layer of complexity.

The tcping still works, but it’s an add-on package and it’s old, so some time soon it may disappear. The telnet is probably not going anywhere, but it’s also an add-on and not good for automated queries.

The answer is to use an all-Bash solution as shown below. In case you’re wondering about the sleep and kill stuff, it is possible that the cat command will time out due to a firewall that quietly drops connections.

if [ -z "" ] || [ -z "" ] ; then exit 1 ; fi
s="$(cat 2>/dev/null < /dev/null > /dev/${p}// & WPID=$!; sleep ${t} && kill $! >/dev/null 2>&1 & KPID=$!; wait $WPID && echo 1)"
echo -ne "\t\t"
echo "${s}" | sed 's/0/2/;s/1/0/;s/2/1/'