Skip to main content

nc - Netcat

Linux 系統中一個多用途的網路工具程式,雖然它只是一個小程式,但是能夠做的事情很多,就像瑞士刀一樣,幾乎任何使用 TCP 或 UDP 封包的動作都可以用它來達成,是許多系統管理者(包含我自己)最喜愛的網路診斷工具之一。

基本指令
# Scanning the port range (20 - 1024)
nc -z 192.168.21.202 20-1024

Connection to 192.168.21.202 22 port [tcp/ssh] succeeded!
Connection to 192.168.21.202 80 port [tcp/http] succeeded!
Connection to 192.168.21.202 111 port [tcp/sunrpc] succeeded!
Connection to 192.168.21.202 443 port [tcp/https] succeeded!
Connection to 192.168.21.202 514 port [tcp/shell] succeeded!

# Scanning the specified port
nc -zv 192.168.21.202 21
nc: connect to 192.168.21.202 port 21 (tcp) failed: Connection refused

# Port Scanning With netcat including displaying version #
echo "QUIT" | nc 192.168.2.17 22
echo "QUIT" | nc -v 192.168.2.254 ssh
# OR pass the -vv  to get remote OpenSSH version # 
nc -vv 192.168.2.254 ssh
檔案傳輸

在不同的 Linux 主機上傳輸檔案

# Install nc and pv
yum install netcat pv

# Machine A with IP : 192.168.0.4
# Machine B with IP : 192.168.0.7
# On Linux Machine A
# [*] tar -zcf = tar is a tape archive utility used to compress/uncompress archive files 
#     and arguments -c creates a new .tar archive file, -f specify type of the archive file 
#     and -z filter archive through gzip.
# [*] CentOS-7-x86_64-DVD-1503.iso = Specify the file name to send over network, it can be file 
#     or path to a directory.
# [*] pv = Pipe Viewer to monitor progress of data.
# [*] nc -l -p 5555 -q 5 = Networking tool used for send and receive data over tcp 
#     and arguments -l used to listen for an incoming connection, -p 555 specifies the source port 
#     to use and -q 5 waits the number of seconds and then quit.
tar -zcf - CentOS-7-x86_64-DVD-1503.iso | pv | nc -l -p 5555 -q 5

# On Linux Machine B
nc 192.168.1.4 5555 | pv | tar -zxf -

複製目錄

# Receiver on hostB
nc -l 5000 | tar xvf -

# Sender on hostA
tar cvf - /path/to/dir | nc hostB.com 5000

Back up host A (/dev/sdb) to host B (sdb-backup.img.gz)

# On host B
nc -l 5000 | dd of=sdb-backup.img.gz

# On host A
dd if=/dev/sdb | gzip -c | nc hostB.com 5000

測試 TCP Port
nc -v 192.168.0.175 5000
UDP 封包傳輸
# 本地主機,傳送字串至遠端主機
echo -n "foo" | nc -u -w1 192.168.1.8 5000

# 遠端主機,開啟 UDP port
nc -lu localhost 5000
掃描目的主機網路埠
# For TCP 
nc -vnz -w 1 192.168.233.208 1-1000 2000-3000

# For UDP
nc -vnzu 192.168.1.8 1-65535
Cheat Sheets

netcat_commands_s.jpg

Reverse Shell

reverse_shell.gif