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.
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...If you like GNU Parallel as much as I do, try this:
Sample Output:
This method is also faster in some cases since it's testing connecting to ports in parallel, not serial. Specifically this would be where the remote host (or intervening firewall) discards your packets to stay stealth (as opposed to a successful connection or forceful reject).
Tip: in most Linux distros, you can install
parallel
from your package manager.Update: With
parallel
, this generalizes super well to cover an often needed case of multiple hosts x multiple ports. The following example usesparallel
to iterate over the cross product, so you don't need to write any nested loops.Output:
Just as the previous example,
parallel
executes the connection tests in parallel. Note, the default parallelism is how many threads your system have, but can override easily with the-j
switch to any value. You could easily get away withparallel -j 50 ...
or even higher since testing sockets is not a CPU intensive task.Netcat is not really a scanner, as the comment suggests nmap would be a better option here. Not using the the port range option I guess you are left with wrapping it in a shell script;
etc..
On Gentoo Linux (with net-analyzer/netcat-110-r9 installed):
In Redhat 6 you could run something like this as a true one-liner:
-z tests port
-n doesn't resolve DNS
-v give verbose output
-w timeout after 2 seconds
; strings one command after another as long as you don't mind typing it out again.
I like the suggestions for using a loop if you are scanning multiple ports, however if it's 2 or 3 and you are already trying to loop through a list with something like SSH, stringing commands like this is useful.