Saturday, June 29, 2013

Netcat for File Transfer

File transfer is one of the most practical usages of netcat.

To transfer a file named filename from client to server, we first issue the following command on server:

nc -l -p 1234 > filename

where 1234 is the port number used by the server. On the client side, we issue:

nc -q 10 server 1234 < filename

where '-q 10' specifies to wait 10 seconds and then quit after EOF on stdin. This would cause the server to quit.

To transfer a director tree named /path from client to server, we issue the following command on server:

nc -l -p 1234 | tar xvzf -

On the client side, we issue:

tar cvzf - /path | nc -q 10 server 1234



If we want to reverse the direction of file transfer, i.e., client pulls file from server, we use:

nc -q 10 -l -p 1234 < filename

on server, and

nc server 1234 > filename

on client. Similarly, to reverse the direction of directory tree transfer, we use:

tar cvzf - /path | nc -q 10 -l -p 1234

on server, and

nc server 1234 | tar xvzf -

on client.

Thursday, June 27, 2013

Using findutils to delete files

Here is a summary from the deleting files page.

The most efficient and secure method to delete any file with name ending in '~' in the directory /path is:

find /path -name \*~ -delete

Using command xargs may allow us to achieve same efficiency but is not as secure:

find /path -name \*~ -print0 | xargs -0 /bin/rm

where '-print0' specifies using ASCII NUL to separate the entries in the file list, and similarly '-0' for command xargs.

If the '-delete' action is not available, we may use action '-execdir' or '-exec':

find /path -name \*~ -execdir /bin/rm {} \+

find /path -name \*~ -exec /bin/rm {} \+

Action '-execdir' is secure but less portable. On the other hand, action '-exec' is most efficient portable but insecure. These two actions can be used for doing things other than deleting files.

Tuesday, June 25, 2013

Use command find to clean up your file system

Some editors create back-up files with the the same file name and a '~' suffix. Once you are done with editing, there is no need to keep these back-up files. The command find allows us to find and remove all such back-up files in working directory:

find . -name \*~ -exec rm {} \;

If you want to remove files not been accessed for more than one year (365 days), you may issue:

find . -atime +365  -exec rm {} \;

Command find comes with many other options, for example, you may use: 'mtime' for last modified, 'ctime' for last change, or even 'inum' for inode number.