Linux – Examining Multiple Ports When Running NetCat (nc)

linuxnetcatportredhat

I am looking to test if specific ports are on a host are open. I am using:

nc -z host 22
nc -z host 80
nc -z host 443
nc -z host 8080

which works, but it would be nice to use a one-liner like:

nc -z host 22 80 443 8080

which doesn't work.

I would like to avoid the port range nc -z host 22-8080 as noted in the man page, if possible, as there is a large gap in port #s I am looking to check. Also, I don't want to scan every port and be seen as scanning for open ports.

Short of writing a bash loop, what are my options for testing if the ports are open? I have dozens of hosts each with a handful of ports to check.

Best Answer

I am using -w 1 below to limit timeouts to 1 second. I also use -v for the reasons mentioned in comments. I used -n to refuse delays for reverse DNS lookups...

[mpenning@tsunami ~]$ for i in $(echo "172.16.1.1,172.16.1.5"|tr "," "\n"); do echo -e "22\n80\n443\n8080" | xargs -i nc -w 1 -zvn $i {}; done
(UNKNOWN) [172.16.1.1] 22 (ssh) open
(UNKNOWN) [172.16.1.1] 80 (www) : Connection timed out
(UNKNOWN) [172.16.1.1] 443 (https) open
(UNKNOWN) [172.16.1.1] 8080 (http-alt) : Connection timed out
(UNKNOWN) [172.16.1.5] 22 (ssh) open
(UNKNOWN) [172.16.1.5] 80 (www) open
(UNKNOWN) [172.16.1.5] 443 (https) open
(UNKNOWN) [172.16.1.5] 8080 (http-alt) : Connection refused
[mpenning@tsunami ~]$
Related Topic