介紹
用來連接特定 port, 或啟動一個 port 來監聽, 可以執行簡單的訊息或檔案傳送
有些系統將 nc 改為 netcat
快速看如何使用
啟動 20000 port
nc -l 192.168.1.171 20000
- 如果不加上 IP, 就會監聽所有從 20000 port 進來的主機
- -l :作為監聽之用,亦即開啟一個 port 來監聽用戶的連線;
- -u :不使用 TCP 而是使用 UDP 作為連線的封包狀態
連線到 20000 port
nc 192.168.1.171 20000
然候就可以隨便打一些字, 送出後主機那就會看到了, 也可搭配 stdout, stdin 做互動輸入/輸出
傳送/接收 檔案
傳送檔案
$ cat backup.iso | nc 54.250.122.78 3333
接收檔案並存入 backup.iso
$ nc -l 3333 >> backup.iso
傳送顯示進度條
$ cat backup.iso | pv -b | nc 54.250.122.78 3333
接收顯示進度條
$ nc -l 8000 | pv -b >> backup.iso
pv
can be used to show a progress indicator.
pv
: Pipe Viewer, 顯示通過 pipe 的資料處理進度, 例如應用在 copy, compress, nc 等等..
傳送 partition
建立一個 partition 的 image 並傳送到遠端主機
$ dd if=/dev/hdb5 | gzip -9 | nc -l 3333
-9, –best : These options change the compression level used, with the -1 option being the fastest, with less compression, and the -9 option being the slowest, with optimal compression. The default compression level is 6.
連到傳送端的 server 並且接收 partition image
$ nc 192.168.0.1 3333 | pv -b > myhdb5partition.img.gz
傳送資料夾
壓縮檔案並傳到遠端主機
$ tar -czf - /etc/ | nc -l 3333
接收檔案
$ nc 192.168.0.1 3333 | pv -b > mybackup.tar.gz
使用 ssh 傳送檔案
有兩個好處 :
- 資料透過加密的通道傳送更為安全
- 你不需要在額外開 port, 因為使用的是 ssh port
You pipe the file to a listening socket on the server machine in the same way as before. It is assumed that an SSH server runs on this machine too.
listen 一個 port 並以 pipe 傳送檔案 (假設 SSH server 已經在這台啟動了)
$ cat backup.iso | nc -l 3333
On the client machine connect to the listening socket through an SSH tunnel:
client server 以 SSH 連到傳送端的主機
$ ssh -f -L 23333:127.0.0.1:3333 me@192.168.0.1 sleep 10; \
nc 127.0.0.1 23333 | pv -b > backup.iso
- 這個方式可以設定當檔案傳送完後自動關閉連線
ssh -f
: Requests ssh to go to background just before command execution. This is useful if ssh is going to ask for passwords or passphrases, but the user wants it in the background.
ssh -L
[bind_address:]port:host:hostport : Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address.
監聽一個範圍 port 的 connection
可以當作 Port Scanner
使用 -z
, netcat 不會 initiate 一個連線到 server, 只會通知這個 port 有找到, 它可以允許 port-range 去掃
例如掃 80~90 的 port, 發送 80 port 有打開 :
$ nc -z 192.168.0.1 80-90
Connection to 192.168.0.1 80 port [tcp/http] succeeded!
ref :
http://linux.vbird.org/linux_server/0140networkcommand.php#nc
http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples/