I would like to test in a script [Linux: CentOS 7] the availability of a remote machine. While TCP packages can blocked by a firewall on the way, ICMP packages may be possible and are not blocked by the default firewall settings. Thus, ping is no help for me
I tried traceroute with a limited number of hops. But I get always an exit code of $?=0 even if the target has not been reached within a given number of hops, e.g.,
traceroute -T -p 1234 192.168.123.45 -w 1 -q 1 -m 5
So, I am looking for a way how to get on the CLI a 'proper error' as exit code if a machine cannot be reached via TCP (for a given set of parameters)?
Solution/Duplicate
Cyrus pointed to Test from shell script if remote TCP port is open which solves my problem with netcat
reading from the tcp pseudo-device may block, when the host does not answer at all on tcp
</dev/tcp/192.168.123.45/1234
thus this would work only for testing ports on reachable hosts. Unfortunately, I found no way to reliable timeout reading from such a pseudo-device (timeout -s4 2 </dev...
does not work)
With netcat probably available on most setups, I am going now for a check like
nc -z -w 2 192.168.123.45 1234 && echo "host foo reachable on port bar" || echo "host foo not reachable on port bar"
with a two second timeout