Wednesday, April 16, 2014

A Simple Netcat How-To for Beginners

There are tonnes of tutorials on Netcat already. This one is to remind me and my colleagues about the awesomeness of nc which we forget on regular basis.
Common situations where nc can be used:
  • Check connectivity between two nodes. I had to learn hard way that ping (read all ICMP) based protocols are not always the best way to judge connectivity. Often ISPs set ICMP to lower priority and drop it.
  • Single file transfer.
  • Testing of network applications. I have written several clients and loggers for logstash and graphite which couldn't have been easier to test without nc.
  • Firing commands to remote servers where running a conventional tcp/http server is not possible (like VMWare ESXi)
Basic Netcat servers:
  • nc -l <port>
    Netcat starts listening for TCP sockets at the specified port. A client can connect and write arbitrary strings to the socket which will be reflected here.
  • nc -u -l <port>
    Netcat starts listening for UDP sockets at the specified port. A client can write arbitrary strings to the socket which will be reflected here.
  • nc -l <port> -e /bin/bash
    Netcat starts listening for TCP sockets at the specified port. A client can connect and write arbitrary commands which will be passed to /bin/bash and executed. Use with extreme caution on remote servers. The security here is nil.
  • nc -l -k <port> -e /bin/bash
    Problem with above command is that nc gets terminated as soon as client disconnects. -k option forces nc to stay alive and listen for subsequent connections as well.
Basic Netcat Clients:
  • nc <address> <port>
    Connect as client to the server running on <address>:<port> via TCP.
  • nc -u <address> <port>
    Connect as client to the server running on <address>:<port> via UDP.
  • nc -w <seconds> <address> <port>
    Connect as client to the server running on <address>:<port> via TCP and timeout after <seconds> of being idle. I used it a lot to send data to graphite using shell scripts.

A cool example to stream any file's content live (mostly used for logs) can be found at commandlinefu.