xiaobaoqiu Blog

Think More, Code Less

Nc命令

nc(netcat)是网络工具中的瑞士军刀。

1.参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
xiaobaoqiu@xiaobaoqiu:~$ nc -h
OpenBSD netcat (Debian patchlevel 1.105-7ubuntu1)
This is nc from the netcat-openbsd package. An alternative nc is available
in the netcat-traditional package.
usage: nc [-46bCDdhjklnrStUuvZz] [-I length] [-i interval] [-O length]
      [-P proxy_username] [-p source_port] [-q seconds] [-s source]
      [-T toskeyword] [-V rtable] [-w timeout] [-X proxy_protocol]
      [-x proxy_address[:port]] [destination] [port]
    Command Summary:
        -4          使用IPv4
        -6          使用IPv6
        -b          允许广播(broadcast)
        -C          每行结尾加上CRLF(回车换行符),即自动换行
        -D          启动debug sock选项
        -d          从stdin解绑(Detach from stdin)
        -h          帮助文档
        -I length   设置TCP接受的buffer长度
        -i secs     设置消息发送及端口扫描时间间隔,单位秒
        -j          Use jumbo frame
        -k          当一个连接结束时,强制nc监听另一个连接。必须和-l一起使用
        -l          监听模式,监听进入进入的连接(inbound connects)
        -n          直接使用IP地址,而不通过域名服务器
        -O length   设置TCP发送的buffer长度
        -P proxyuser    代理权限使用的用户名
        -p port     设置本地主机使用的通信端口
        -q secs     quit after EOF on stdin and delay of secs
        -r          随机指定本地主机使用的通信端口
        -S          Enable the TCP MD5 signature option
        -s addr     设置本地主机送出数据包的IP地址
        -T toskeyword   指定链接的IP服务类型
        -t          Answer TELNET negotiation
        -U          Use UNIX domain socket
        -u          使用UDP传输协议
        -V rtable   指定可选的路由表
        -v          显示指令执行过程
        -w secs     设置连接的超时时间,单位秒
        -X proto    指定代理协议: "4", "5" (SOCKS) or "connect"
        -x addr[:port]  指定代理地址和端口号
        -Z          DCCP mode
        -z          0输入输出模式(只在端口扫描的时候使用)

    注意:参数中端口号可以为单个端口,也可以是端口区间:low-high(闭区间)

2.典型使用case

下面列举了几个典型的使用,更多使用case参见: http://xmodulo.com/useful-netcat-examples-linux.html

2.1.文件传输

在线上机器和本地机器之间传输文件,使用scp的话通常需要多次scp,并且通常需要密码,这是nc命令就显示其强大之处:

文件源端:

1
sudo cat abc.gz | nc -l 192.168.111.222 45678

文件目的端:

1
nc 192.168.111.222 45678 > abc.gz

2.2.端口扫描

测试远端机器的某一个端口是否打开,succeeded表示打开:

1
2
3
4
5
xiaobaoqiu@xiaobaoqiu:~$ nc -v -w 2 192.168.111.222 -z 21-24
Connection to 192.168.111.222 21 port [tcp/ftp] succeeded!
Connection to 192.168.111.222 22 port [tcp/ssh] succeeded!
nc: connect to 192.168.111.222 port 23 (tcp) failed: Connection refused
nc: connect to 192.168.111.222 port 24 (tcp) failed: Connection refused

2.3.简单聊天工具

一端打开:

1
2
3
xiaobaoqiu@xiaobaoqiu:~$ nc -l 1234
hello
yes

另外一端连接,就可以聊天了:

1
2
3
xiaobaoqiu@xiaobaoqiu:~$ nc 192.168.111.222 1234
hello
yes

3.参考

http://xmodulo.com/useful-netcat-examples-linux.html

http://mylinuxbook.com/linux-netcat-command/