man 手冊介紹
The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP. It can open TCP connections, sendUDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6. Unlike telnet(1), nc scripts nicely, and separates error messages onto standard error instead of sending them to standard output, as telnet(1) does with some.
nc 功能簡介
nc是網絡界的“瑞士軍刀”, 提供以下功能:
- 監聽特定的端口,這時候
nc
可以作為一個服務器,不過僅僅是一個echo服務器 - 鏈接特定的端口,這時候
nc
就成為一個客戶端,也是一個簡單的客戶端,只能起echo作用 - 掃描端口,這可以查詢某個機器上是否開啟了某個端口
語法格式
nc
語法格式過長,具體的可以查閱man手冊,本文只介紹常用的幾個選項
- -l Listen mode, for inbound connects 監聽模式,接收鏈接
- -p port Specify local port for remote connects 指定一個本地端口去鏈接遠端服務器
- -w secs Timeout for connects and final net reads 接收一個連接到第一個消息到來的超時時間
例子說明
監聽端口
語法格式:nc -l [addr] port
說明:如果不指定addr
,則綁定地址0.0.0.0,即該機器所綁定的所有網卡ip都能鏈接上指定的port
不指定IP
[root@localhost103 ~]$ nc -l 1234
[root@localhost103 ~]$netstat -tunlp | grep 1234
tcp 0 0 0.0.0.0:1234 0.0.0.0:* LISTEN 22304/nc
指定IP
[root@localhost103 ~]$ nc -l 127.0.0.1 1234
[root@localhost103 ~]$netstat -tunlp | grep 1234
tcp 0 0 127.0.0.1:1234 0.0.0.0:* LISTEN 23805/nc
鏈接指定IP PORT
語法格式:nc IP PORT [-p port]
說明:IP
PORT
為目的機器的地址,可選項 -p port 為以本機指定的端口port
鏈接目的地址
目標機器地址為:127.0.0.1 1234
nc 127.0.0.1 1234 #直接則鏈接上目標機器
掃描端口
語法格式:nc -v -z port1-prot2
說明:-v
是打印出詳細信息 -z
是指定端口區間
[root@localhost103 ~]$ nc -v 192.168.201.75 -z 7000-7010
nc: connect to 192.168.201.75 port 7000 (tcp) failed: Connection refused
Connection to 192.168.201.75 7001 port [tcp/afs3-callback] succeeded!
Connection to 192.168.201.75 7002 port [tcp/afs3-prserver] succeeded!
nc: connect to 192.168.201.75 port 7003 (tcp) failed: Connection refused
Connection to 192.168.201.75 7004 port [tcp/afs3-kaserver] succeeded!
Connection to 192.168.201.75 7005 port [tcp/afs3-volser] succeeded!
Connection to 192.168.201.75 7006 port [tcp/afs3-errors] succeeded!
Connection to 192.168.201.75 7007 port [tcp/afs3-bos] succeeded!
Connection to 192.168.201.75 7008 port [tcp/afs3-update] succeeded!
Connection to 192.168.201.75 7009 port [tcp/afs3-rmtsys] succeeded!
Connection to 192.168.201.75 7010 port [tcp/ups-onlinet] succeeded!
總結
nc
功能實則很強大,還可以做簡單的代理服務器、傳送文件等等功能,號稱網絡中的瑞士軍刀,也不是浪得虛名,工具雖然強大,但還在乎于使用的人。關于該命令,還將持續學習中,以此做記錄。