Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question
1  
why aren't you using nmap? –  Mike Pennington Jul 23 '12 at 21:09
    
@MikePennington: nmap is not installed and I don't have access to install it. –  KM. Jul 23 '12 at 21:14
    
FYI, you need to use nc -zv hostname port; if you do this without -v, then you won't get feedback on whether the port is open or closed (at least for my version of nc on Debian Squeeze) –  Mike Pennington Jul 23 '12 at 21:19
    
@MikePennington: My version on redhat is fine with -z (so far). So, nmap it is, eh? –  KM. Jul 23 '12 at 21:24

2 Answers 2

up vote 3 down vote accepted

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 ~]$
share|improve this answer
    
Thanks for the answer and suggestion to look at nmap. –  KM. Jul 24 '12 at 16:23

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;

    for host in $(cat hostlist); do
        for port in $ports; do nc -z $host $port; done
    done

etc..

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.