Netcat学习笔记

简介

Netcat 是一个功能强大的网络工具,常被用于端口扫描、文件传输等。在 macOS 系统中直接使用 brew install netcat 进行安装,调用命令为 nc

常用参数

使用 nc -h 查看使用帮助。常用参数如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Options:
-c, --close close connection on EOF from stdin
-e, --exec=PROGRAM program to exec after connect
-g, --gateway=LIST source-routing hop point[s], up to 8
-G, --pointer=NUM source-routing pointer: 4, 8, 12, ...
-h, --help display this help and exit
-i, --interval=SECS delay interval for lines sent, ports scanned
-l, --listen listen mode, for inbound connects
-L, --tunnel=ADDRESS:PORT forward local port to remote address
-n, --dont-resolve numeric-only IP addresses, no DNS
-o, --output=FILE output hexdump traffic to FILE (implies -x)
-p, --local-port=NUM local port number
-r, --randomize randomize local and remote ports
-s, --source=ADDRESS local source address (ip or hostname)
-t, --tcp TCP mode (default)
-T, --telnet answer using TELNET negotiation
-u, --udp UDP mode
-v, --verbose verbose (use twice to be more verbose)
-V, --version output version information and exit
-x, --hexdump hexdump incoming and outgoing traffic
-w, --wait=SECS timeout for connects and final net reads
-z, --zero zero-I/O mode (used for scanning)

Remote port number can also be specified as range. Example: '1-1024'

端口扫描

对特定的几个端口进行扫描:

1
nc -zv 192.168.1.100 22 80 443 3389

对端口范围进行扫描:

1
nc -zv 192.168.1.100 20-80

端口监听

使用 -l 参数开启端口监听:

1
nc -l -p 6666

文本传输

Netcat 可以双向实时传输文本,就像使用 IM 工具聊天一样。

开启接收端:

1
nc -l -p 6666

开启发送端

1
nc 127.0.0.1 6666

连接上之后,发送方可以向接收方发送消息,接收方也可以像发送方发送消息,这个功能甚至可以用做 Windows、macOS、Linux 之间的跨设备剪贴板。

文件传输

先开启接收端对指定端口进行监听:

1
nc -l -p 6666 > 1.png

然后发送端读取本地文件并进行发送:

1
nc 127.0.0.1 6666 < 1.png

Netcat 本身只能传文件流,不能直接传文件夹。我们需要结合 tar 命令先打包再发送。这种方式非常适合备份或迁移项目代码。

开启接收端:

1
nc -l -p 12345 | tar xzvf -

开启发送端:

1
tar czvf - my_folder/ | nc 127.0.0.1 12345

流媒体播放

视频播放需要先安装播放器,我使用的是 mplayer。

1
brew install mplayer

先开启接收端并指定视频播放帧率:

1
nc -l -p 6666 | mplayer -fps 30 -cache 1024 -

然后开启发送端:

1
cat 1.mp4 | nc 127.0.0.1 6666