NetCat的一些小技巧

功能超级强大的网络工具netcat

A机器执行 nc -l 1234
B机器执行 nc a-ip 1234
AB之间就可以联通了, 可以当聊天工具用。

A机器执行 nc -l 1234 -e /bin/bash -k
B机器执行 nc a-ip 1234
B机器就可以运行A机器的shell了, -k 相当于 –keep-open,保持连接 可以接多会话。

A机器执行 tailf /var/log/nginx/access.log | nc -l 1234 -k
B机器执行 nc a-ip 1234
B机器就可以实时看A机器的日志了。

A机器执行 nc -l 1234 < file.txt
B机器执行 nc a-ip 1234 > file.txt
B机器就可以下载到A机器的文件了。

使用Netcat在两台服务器之间传输文件

To send a directory, cd to inside the directory whose contents you want to send on the computer doing the sending and do:

tar -cz . | nc -q 10 -l -p 45454

On the computer receiving the contents, cd to where you want the contents to appear and do:

nc -w 10 $REMOTE_HOST 45454 | tar -xz

Replace $REMOTE_HOST with ip / hostname of computer doing the sending. You can also use a different port instead of 45454.

What’s actually happening here is that the ‘receiving’ computer is connecting to the sending computer on port 45454 and receiving the tar’d and gzip’d contents of the directory, and is passing that directly to tar (and gzip) to extract it into the current directory.

Quick example (using localhost as a remote host)

Computer 1

caspar@jumpy:~/nctest/a/mydir$ ls
file_a.txt file_b.log
caspar@jumpy:~/nctest/a/mydir$ tar -cz . | nc -q 10 -l -p 45454
Computer 2

caspar@jumpy:~/nctest/b$ ls
caspar@jumpy:~/nctest/b$ nc -w 10 localhost 45454 | tar -xz
caspar@jumpy:~/nctest/b$ ls
file_a.txt file_b.log