netcat (nc) [網絡上的利刀]

更新時間: 2018-09-21





apt-get install netcat




# it handles binary data as regular data

nc -t

# use another source ip

nc -s <source_ip> -t <target> 25


-s, --source addr

-p, --source-port port

-C, --crlf                            # Use CRLF for EOL sequence


Port_Listening (Chatting)


nc -l -p 12345


Transferring File


Transfer File

Receiver Side

nc -v -l 6666 | gzip -d | pv > vda.qcow2

 * gzip 比 bzip2 有效

raw:    real 0m19.214s           # 96 MiB/s (Disk IO Limit)

gzip:   1.88GiB -> 873MiB      real 1m17.842s # 11.2 MiB/s

bzip2: 1.88GiB -> 818MiB      real 3m20.568s

-v               # Have nc give more verbose output.

Listening on [] (family 0, port 6666)
Connection from localhost.localdomain 52152 received!

# Sender Side

gzip -c vda.qcow2 | pv | nc -w 3 6666

Clone Disk

# Destination

# 使用 lz4 取代 gzip 有較好 performance

nc -v -l -p 6666 | gzip -d | dd bs=16M of=/dev/sdb

# Source

dd bs=16M if=/dev/sda | gzip -c | nc -w 3 serverB 6666

Transfer with md5 checksum



netcat terminate when stdin closes


Sender 用 -w 及 -q; Receiver 不用 -N 都得


-w timeout   # Connections which cannot be established or are idle timeout after timeout seconds.

-q seconds   # after EOF on stdin, wait the specified number of seconds and then quit.

                  # If seconds is negative, wait forever (default).  "0" 代表立即關

                  # Specifying a non-negative seconds implies -N

-N               # shutdown the network socket after EOF on the input.


Port Scanning


$ nc -v -n -z -w 1 1-1000

-n     # prevents DNS lookup

-z     # Zero-I/O mode. In both cases, no data is transfered.

In connect mode

it means that as soon as the port is open it is immediately shutdown and closed.

In listen mode

it makes netcat refusing all the incoming connections thus running in timeout (if set), or waiting forever.

-w1   # makes the connection timeout after 1 second of inactivity



nc -z -w 1 1433

Connection to 1433 port [tcp/ms-sql-s] succeeded!


nc -z -w 1 1434

echo $?




-u      # Use UDP instead of the default option of TCP.

-v      # Have nc give more verbose output.

-w N  # sec


nc -v  -w 1 -u 500

Connection to 500 port [udp/isakmp] succeeded!

 * 加 -v 後, 會有 3 個 udp package 發去對方.

# nc send single udp packet

echo '' | nc -u -w 1 4001




# Input (TCP Port: 1234) --> Web --> Output (TCP Port: 2345)

$ nc -l -p 1234 | nc 80 | nc -l -p 2345




$ nc -l -p 12345 -e /bin/bash


Port response


# until ssh port has response

until nc -vzw 2 $IP 22; do sleep 2; done




mon a port & e-mail alarm


msg="IPSec_Fail - Server-X"
email="admin@domain1 admin@domain2"

# check mssql
nc -z -w 1 1433

if [ $? != 0 ];then
    echo $msg
    echo "$msg" | mail -s "$msg" $email


Window 的 nc