I was just looking around info about netcat
and telnet
, trying to understand a bit more. Well… in few words: no point to install telnet if you have netcat! 🙂 Netcat is perfect for scripting, ’cause it’s non-interactive, UDP/TCP capable, can be a listener as well… very powerful tool. Here some example.
How to check if your httpd is up and running:
~ $ nc -zv localhost 80
Connection to localhost 80 port [tcp/http] succeeded!
…and it closes gracefully 😉
How to check port-range ports:
~ $ nc -zv localhost 20-25
nc: connect to localhost port 20 (tcp) failed: Connection refused
Connection to localhost 21 port [tcp/ftp] succeeded!
Connection to localhost 22 port [tcp/ssh] succeeded!
nc: connect to localhost port 23 (tcp) failed: Connection refused
nc: connect to localhost port 24 (tcp) failed: Connection refused
nc: connect to localhost port 25 (tcp) failed: Connection refused
… or a list of ports:
$ nc -zv localhost 20 22 80 443
nc: connect to localhost port 20 (tcp) failed: Connection refused
Connection to localhost 22 port [tcp/ssh] succeeded!
Connection to localhost 80 port [tcp/http] succeeded!
Connection to localhost 443 port [tcp/https] succeeded!
NOTE: If you want to grep or play with the “output” of the command, you need to use 2>&1
For example:
nc -zv localhost 1-1024 <strong>2>&1</strong> | grep succeeded
How to check the service that’s running on that port:
(From man) Alternatively, it might be useful to know which server software is running, and which versions. This information is often contained within the greeting banners. In order to retrieve these, it is necessary to first make a connection, and then break the connection when the banner has been retrieved. This can be accomplished by specifying a small timeout with the -w flag, or perhaps by issuing a “QUIT” command to the server:
$ echo "QUIT" | nc host.example.com 20-30
SSH-1.99-OpenSSH_3.6.1p2
Protocol mismatch.
220 host.example.com IMS SMTP Receiver Version 0.84 Ready
In some cases, it’s handy to add -q 1 at the end, if nc hangs (I’ve noticed this in some cases) Like this:
$ echo "QUIT" | nc host.example.com 20-30 <strong>-q 1</strong>
Or how to send/receive a file:
On the receiver side:
$ nc -l 1234 > /tmp/file_to_receive
On the sender side:
$ cat file_to_send | nc receiver_ip_or_fqdn 1234
or
$ nc receiver_ip_or_fqdn 1234 < file_to_send
There are plenty of things that you can do. These are just simple examples… enjoy! 🙂