}

How to transfer files over the network using Netcat

Created:

Introduction

Netcat is a helpful tool when you are in a hurry to transfer files between machines. Learning this tool is a must have skill for any devops, it or software developer. Usually people transfer files using SCP, FTP, SMB but sometimes you don't want to waste time configuring a service.

IMPORTANT netcat uses plain transfer. if you want to send confidential information you should encrypt your data before sending it to the network.

Using Netcat

You will have one netcat that will send data and the other one for receiving.

Receiving side

nc -l -p 9999 > received_file.txt

Netcat will start to listen on the port 9999 and the result will be save to the received_file.txt. If you don't redirect stdout the data received will be printed on screen.

Sending side

nc 192.168.0.1 9999 < received_file.txt

When you are sending you need to specify the address (192.168.0.1) and the port (9999). We redirected the content of the file to netcat, note the order of the "<" is the inverse of the receiving side. You can use -w paramter of the nc command to specify a timeout.

Compressing

You can use linux pipes to compress and decompress

Receiving side

The receiving side will first xz, the -c flag is writting to the stdout and -d for decompress. Since uncompress writes to the stdout, then tar will finally unpack the uncompressed data.

nc -l -p 9999 | xz -dc | tar xvf -

Sending side

On the sending side we first use tar to pack the directory and then we pipe to xz, when data is compressed we redirect compressed stdout to nc command.

tar cvf - . | xz -c | nc 192.168.0.1 9999

Cool tips

Use netcat to transfer the whole disk

On the sending side we use dd and compress with xz:

dd if=/dev/hda3 | xz -c | nc -l 9595

For receiving:

nc 192.168.0.1 9595 | pv -b > hardrive_backup.img.xz

The pv command allows a user to see the progress of data through a pipeline. We save the hard drive image to a file.