February 23, 2009

"nc" the real gem

It is quite simple to build a very basic client/server model using nc. On one console, start nc listening on a specific port for a connection. For example:

$ nc -l 1234

nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:

$ nc 127.0.0.1 1234

There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After the connection has been set up, nc does not really care which side is being used as a ‘server’ and which side is being used as a ‘client’. The connection may be terminated using an EOF (‘^D’).

DATA TRANSFER
The example in the previous section can be expanded to build a basic data transfer model. Any information input into one end of the connection will be output to the other end, and input and output can be easily captured in order to emulate file transfer.

Start by using nc to listen on a specific port, with output captured into a file:

# nc -l 1235 > filename.out

Using a second machine, connect to the listening nc process, feeding it the file which is to be transferred:

[other_server]# time nc 172.29.0.99 1235 < some_big_seven_gb.sql

real 12m58.870s
user 0m2.953s
sys 0m26.079s

Compare these results with the scp command :

real 13m45.413s
user 1m55.461s
sys 0m37.628s

_____

The only way to improve the file transfer performance is to compress the file before sending using zip or bzip2

Let's assume you want to transfer a 66 MB SQL text file (revert_15_april.sql) from local server to remote server in less than 2 minutes.

(sending server 10.10.10.1)
tar jcf - revert_15_april.sql | nc -l 1234

(Receiving server)
nc 10.10.10.1 1234 | tar jxf -

It is also possible to send all the files from current folder just by replacing the file name with *
tar jcf - * | nc -l 1234

### Or the same can also be done using...

(Receiving server)
## start listening : ##
nc -l 8888 | tar jxf -

(sending server)
## cd to the directory that you want to copy and push all to server 172: ##
tar jcf - . | nc 172.172.172.172 8888

_____

You can also send directory using NetCat to another server as a single file...

Sending Server:
tar c test | nc -l 7878

Receiving Server:
nc 10.10.10.1 7878 > backup.tar

# to extract the file, use the standard tar command.
tar xvf backup.tar

_____

Copy data from one server to another.

Sending server:
mysqldump db_name tbl_name | bzip2 -c | nc -l 1234

Receiving server:
nc 10.10.10.14 1234 | bzip2 -cd | mysql -uroot -proot@123 db_name

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.