Originally published December 27, 2016 @ 11:04 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. 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.

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