linux下的nc命令使用

nc是一个看似简单的命令,建立一条tcp/udp连接而已,不过其实用处很大。

数据传输

使用scp传输大文件时,比如1TB,会比较慢,因为所有的数据都会加密传输,加密也会更耗CPU,此时使用nc可以解决这一问题:

#server
nc -l 1234 > data.txt
#client
nc -N xx.xx.xx.xx 1234 < data.txt

上面的-N表示数据传完了(EOF),自动断开连接退出。如果不考虑这一特点(即不知道什么时候传完了),其实数据传输是双向的,下载数据就可以直接调整一下尖括号方向,写成:

#server
nc -l 1234 < data.txt
#client
nc xx.xx.xx.xx 1234 > data.txt

文件夹传输,服务端将一个目录传输给连接过来的客户端:

#server
tar -cvf – dir_name | nc -l 1234
#client
nc xx.xx.xx.xx 1234 | tar -xvf -

压缩传输也很easy哦:

#server
tar -zcvf – dir_name | nc -l 1234
#client
nc xx.xx.xx.xx 1234 | tar -zxvf -

端口扫描

端口扫描,可以指定端口,也可以指定端口范围:

nc -zv xx.xx.xx.xx 135-1000
nc -zv xx.xx.xx.xx 22 80 443 8080

端口扫描只是扫描端口能否连上,并不表示能正常通信,可以使用如下命令获取版本:

$ echo "QUIT" | nc xx.xx.xx.xx 22
SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2

$ echo "QUIT" | nc xx.xx.xx.xx 80
HTTP/1.1 400 Bad Request
Server: nginx
Date: Thu, 06 Apr 2017 03:53:21 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 166
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>

远程备机

配合dd命令,将磁盘拷贝到远程机器:

#server
$ dd if=/dev/sda | nc -l 1234
#client
$ nc -n 192.168.1.1 1234 | dd of=/dev/sda

远程终端

希望别人帮忙,但又不想把密码告诉别人,这个时候需要开启一个远程终端,使用如下命令搞定:

#server
$ mkfifo /tmp/tmp_fifo
$ cat /tmp/tmp_fifo | /bin/bash -i 2>&1 | nc -l 20000 > /tmp/tmp_fifo
#client
nc xx.xx.xx.xx 20000

 

发表于 2017年04月06日 12:08   修改于 2023年10月09日 11:57   评论:0   阅读:5591  



回到顶部

首页 | 关于我 | 关于本站 | 站内留言 | rss
python logo   django logo   tornado logo