How to transfer files between servers using Netcat
On linux/unix environments scp are rsyncare widely used to transfer/synchronize files between servers since they provide a secure way to transfer files between two or more computer nodes.
Quickly:
me@server1 ~ % nc -l -p 4444 < file.txt
me@server2 ~ % nc -w 3 server1 4444 > file.txt
Netcat for file transfer is extremely insecure and may only be used when security is not the concern And you have a big file. Otherwise, use scp or rsync.
If you really have to use netcat, here an example of how to do that:
Install netcat:
freebsd: pkg install netcat
redhat/centos: yum install netcat
ubuntu: apt install netcat
archlinux: pacman -S netcat
Scneario
Considering you want to transfer a file from server_1 to server_2. Or better talking in netcat way: Getting a file on server_1 from server_2:
Transfering
From server_1, where the file “bigfile.txt” exist:
user@server1 ~ % nc -l -p 4444 < bigfile.txt
Arguments:
-l, — listen: listen mode, for inbound connects
-p, — local-port=NUM: local port number
From server_2, who will get the file from server_1:
user@server2 ~ % nc -w 3 server1 4444 > bigfile.txt
Arguments:
-w, — wait=SECS: timeout for connects and final net reads
In case you want to see the progress, install pv (pipe viewer) and add to nc command:
Please note that if netcat is installed and the nc command is not available, netcat is probably represented by ncat and/or netcat command.
Some use-cases
- You have an iso file in a dev server and would like to transfer it to another one and security is not a problem.
- You have a big system library on one dev server and would like to transfer to another one and security is not a problem.
- You don’t want to bother the dev server ssh process and you just have a simple iso file to transfer and security is not a problem.
Conclusion
Again, netcat is insecure and is not to be used as file transfer. Use it only if you have to, otherwise use scp or rsync.
References