Scan and test open ports with netcat


Posted:   |   More posts about tip sysadmin

Many already know that netcat (or nc, its shortcut defined on many systems) has been defined the Sysadmin' Swiss Army knife. Lets take a look at some tips useful to test if some ports are really opened on a system.

Of course we could use nmap but sometimes it is not available. Thankfully we can make a port scan simply by firing:

$ nc -vz targethost.tld 1-1024

Above command has the tradeoff that you'll get your screen full of error messages like:

nc: connect to targethost.tld port 1 (tcp) failed: Connection refused
nc: connect to targethost.tld port 2 (tcp) failed: Connection refused
nc: connect to targethost.tld port 3 (tcp) failed: Connection refused
nc: connect to targethost.tld port 4 (tcp) failed: Connection refused
nc: connect to targethost.tld port 5 (tcp) failed: Connection refused
nc: connect to targethost.tld port 6 (tcp) failed: Connection refused
nc: connect to targethost.tld port 7 (tcp) failed: Connection refused

To avoid this redirect stdout and stderr to grep to filter only information about open ports found:

$ nc -v -z  1-1024 2>&1 | grep -v failed

Sometimes target under test is behind a firewall and we want to be sure that the rule we have applied to open a port is working. But what if customer still hasn't any service listening on that port? Of course nc will help us. Run the following on the target machine (in case you are testing 8002 port):

$ nc -l 8002

This will make the program listen for incoming TCP connections on port 8002. Now from another server:

$ nc targethost.tld 8002

nc will prompt and, if everything went well, we should read what we write here @ targethost.tld

This amazing tool can help the sysadmin' life in other ways (file transfer, remote shell) and maybe I'll post about them in the future, in the meanwhile:

$ man netcat