I wanted to write a quick entry about netcat and some of the things I have used it for, but after sitting down and getting started I quickly realised that netcat is one of those commands that deserves more that just a few lines.
WHAT IS NETCAT?
Netcat is a cli based tool that allows reading from and writing network connections via either TCP or UDP. It’s almost the same as a telnet client, but much more scriptable. Netcat has three main modes of functionality which are: connect mode, listen mode, and tunnel mode.
In 2000, according to www.insecure.org, Netcat was voted the second most functional network security tool and is described as “a TCP/IP Swiss army knife” -An impressive feat when you consider that it is just a single binary file which takes up less than 30KB on a standard Ubuntu install. I am a big fan of small, simple applications which do one job and do it very well as opposed to large bloated software packages. I believe it is for this reason netcat is so popular.
Listed below are a few examples demonstrating the functionality and versatility of netcat.
nc -vz localhost 1-1023 2>&1 | grep succeeded
“2>&1” is because we want to redirect stderr (2) and stdout (1) to a file for manipulation by grep in this instance.
Start the session on one machine:
nc -l 1234
Connect to the session from another machine:
nc 220.127.116.11 1234
You have now started a chat session, simply start typing your message and when you hit the return key your message will appear on the other machine.
Nectat can also be used to set up a telnet server. You can specify bash or indeed any executable you want netcat to run at a successful connection with the -e parameter:
nc -l 1234 -e /bin/bash
Start by using nc to listen on a specific port, with output captured into a file:
nc -l 1234 > sending.file
Using a second machine, connect to the listening nc process, feeding it the file which is to be transferred:
nc host.example.com 1234 < receiving.file
Usually whilst mucking around with my apache configs this is the script I like to run to display a simple “This page is currently offline for maintenance” page after stopping the apache services of course.
while true; do sudo nc -l 80 < /path/to/down_for_maintenance.html; done
If you want to redirect your website using netcat to another page entirely you can do so using the following commands:
First you will need to create a named pipe to allow inter-process communication:
Then redirect your webserver using the following command:
while true; do sudo nc -l 80 0<redirect | nc www.backuphomecomputerlab.com 80 1>redirect; done
COPY A HARD DRIVE PARTITION TO AN IMAGE FILE ACROSS THE NETWORK
Run this command on the machine where you would like to save the image to:
nc -l -p 1234 | dd of=/path/to/save/image.iso
Run this command on the machine whose hard drive you would like to image:
dd if=/dev/sda | nc 18.104.22.168 1234