nc 命令使用小結(jié)

前言

nc是netcat的簡(jiǎn)寫(xiě),有著網(wǎng)絡(luò)界的瑞士軍刀美譽(yù)掀泳。因?yàn)樗绦【贰⒐δ軐?shí)用西轩,被設(shè)計(jì)為一個(gè)簡(jiǎn)單员舵、可靠的網(wǎng)絡(luò)工具。比如大家很熟悉使用telnet測(cè)試tcp端口藕畔,而nc可以支持測(cè)試linux的tcp和udp端口马僻,而且也經(jīng)常被用于端口掃描,甚至把nc作為server以TCP或UDP方式偵聽(tīng)指定端口做簡(jiǎn)單的模擬測(cè)試注服。

更新歷史

2020年10月07日 - 初稿

閱讀原文 - https://wsgzao.github.io/post/nc/


nc簡(jiǎn)介

ncat 或者說(shuō) nc 是一款功能類似 cat 的工具韭邓,但是是用于網(wǎng)絡(luò)的。它是一款擁有多種功能的 CLI 工具溶弟,可以用來(lái)在網(wǎng)絡(luò)上讀女淑、寫(xiě)以及重定向數(shù)據(jù)。 它被設(shè)計(jì)成可以被腳本或其他程序調(diào)用的可靠的后端工具辜御。同時(shí)由于它能創(chuàng)建任意所需的連接鸭你,因此也是一個(gè)很好的網(wǎng)絡(luò)調(diào)試工具。

ncat/nc 既是一個(gè)端口掃描工具擒权,也是一款安全工具苇本,還能是一款監(jiān)測(cè)工具,甚至可以做為一個(gè)簡(jiǎn)單的 TCP 代理菜拓。 由于有這么多的功能瓣窄,它被譽(yù)為是網(wǎng)絡(luò)界的瑞士軍刀。 這是每個(gè)系統(tǒng)管理員都應(yīng)該知道并且掌握它纳鼎。

在大多數(shù) Debian 發(fā)行版中俺夕,nc 是默認(rèn)可用的裳凸,它會(huì)在安裝系統(tǒng)的過(guò)程中自動(dòng)被安裝。 但是在 CentOS 7 / RHEL 7 的最小化安裝中劝贸,nc 并不會(huì)默認(rèn)被安裝姨谷。 你需要用下列命令手工安裝。

# 安裝nc
[root@localhost wangao]# yum provides nc
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centos.usonyx.net
 * extras: centos.usonyx.net
 * updates: centos.usonyx.net
2:nmap-ncat-6.40-19.el7.x86_64 : Nmap's Netcat replacement
Repo        : base
Matched from:
Provides    : nc

# 執(zhí)行nc或者nmap-ncat安裝都可以
yum install nmap-ncat -y

# 我們通過(guò) ll 命令查看 nc 命令, 老版本對(duì)應(yīng)的ncat映九,新版本則直接指向nmap
ll /usr/bin/nc
lrwxrwxrwx. 1 root root 4 Feb 19 19:09 /usr/bin/nc -> ncat

[root@localhost wangao]# ll /usr/bin/nc
lrwxrwxrwx. 1 root root 22 Oct  8 11:25 /usr/bin/nc -> /etc/alternatives/nmap

nc常用命令

nc的作用:

  1. 實(shí)現(xiàn)任意TCP/UDP端口的偵聽(tīng)梦湘,nc可以作為server以TCP或UDP方式偵聽(tīng)指定端口
  2. 端口的掃描,nc可以作為client發(fā)起TCP或UDP連接
  3. 機(jī)器之間傳輸文件
  4. 機(jī)器之間網(wǎng)絡(luò)測(cè)速

nc的控制參數(shù)不少件甥,常用的幾個(gè)參數(shù)如下所列:

  1. -l

用于指定nc將處于偵聽(tīng)模式捌议。指定該參數(shù),則意味著nc被當(dāng)作server引有,偵聽(tīng)并接受連接瓣颅,而非向其它地址發(fā)起連接。

  1. -p <port>

暫未用到(老版本的nc可能需要在端口號(hào)前加-p參數(shù))

  1. -s

指定發(fā)送數(shù)據(jù)的源IP地址譬正,適用于多網(wǎng)卡機(jī)

  1. -u

指定nc使用UDP協(xié)議宫补,默認(rèn)為T(mén)CP

  1. -v

輸出交互或出錯(cuò)信息,新手調(diào)試時(shí)尤為有用

6)-w

超時(shí)秒數(shù)曾我,后面跟數(shù)字

7)-z

表示zero粉怕,表示掃描時(shí)不發(fā)送任何數(shù)據(jù)

NAME
       ncat - Concatenate and redirect sockets

SYNOPSIS
       ncat [OPTIONS...] [hostname] [port]

DESCRIPTION
       Ncat is a feature-packed networking utility which reads and writes data across networks
       from the command line. Ncat was written for the Nmap Project and is the culmination of
       the currently splintered family of Netcat incarnations. It is designed to be a reliable
       back-end tool to instantly provide network connectivity to other applications and users.
       Ncat will not only work with IPv4 and IPv6 but provides the user with a virtually
       limitless number of potential uses.

       Among Ncat's vast number of features there is the ability to chain Ncats together;
       redirection of TCP, UDP, and SCTP ports to other sites; SSL support; and proxy
       connections via SOCKS4 or HTTP proxies (with optional proxy authentication as well).
       Some general principles apply to most applications and thus give you the capability of
       instantly adding networking support to software that would normally never support it.

OPTIONS SUMMARY
           Ncat 7.50 ( https://nmap.org/ncat )
           Usage: ncat [options] [hostname] [port]

           Options taking a time assume seconds. Append 'ms' for milliseconds,
           's' for seconds, 'm' for minutes, or 'h' for hours (e.g. 500ms).
             -4                         Use IPv4 only
             -6                         Use IPv6 only
             -U, --unixsock             Use Unix domain sockets only
             -C, --crlf                 Use CRLF for EOL sequence
             -c, --sh-exec <command>    Executes the given command via /bin/sh
             -e, --exec <command>       Executes the given command
                 --lua-exec <filename>  Executes the given Lua script
             -g hop1[,hop2,...]         Loose source routing hop points (8 max)
             -G <n>                     Loose source routing hop pointer (4, 8, 12, ...)
             -m, --max-conns <n>        Maximum <n> simultaneous connections
             -h, --help                 Display this help screen
             -d, --delay <time>         Wait between read/writes
             -o, --output <filename>    Dump session data to a file
             -x, --hex-dump <filename>  Dump session data as hex to a file
             -i, --idle-timeout <time>  Idle read/write timeout
             -p, --source-port port     Specify source port to use
             -s, --source addr          Specify source address to use (doesn't affect -l)
             -l, --listen               Bind and listen for incoming connections
             -k, --keep-open            Accept multiple connections in listen mode
             -n, --nodns                Do not resolve hostnames via DNS
             -t, --telnet               Answer Telnet negotiations
             -u, --udp                  Use UDP instead of default TCP
                 --sctp                 Use SCTP instead of default TCP
             -v, --verbose              Set verbosity level (can be used several times)
             -w, --wait <time>          Connect timeout
             -z                         Zero-I/O mode, report connection status only
                 --append-output        Append rather than clobber specified output files
                 --send-only            Only send data, ignoring received; quit on EOF
                 --recv-only            Only receive data, never send anything
                 --allow                Allow only given hosts to connect to Ncat
                 --allowfile            A file of hosts allowed to connect to Ncat
                 --deny                 Deny given hosts from connecting to Ncat
                 --denyfile             A file of hosts denied from connecting to Ncat
                 --broker               Enable Ncat's connection brokering mode
                 --chat                 Start a simple Ncat chat server
                 --proxy <addr[:port]>  Specify address of host to proxy through
                 --proxy-type <type>    Specify proxy type ("http" or "socks4" or "socks5")
                 --proxy-auth <auth>    Authenticate with HTTP or SOCKS proxy server
                 --ssl                  Connect or listen with SSL
                 --ssl-cert             Specify SSL certificate file (PEM) for listening
                 --ssl-key              Specify SSL private key (PEM) for listening
                 --ssl-verify           Verify trust and domain name of certificates
                 --ssl-trustfile        PEM file containing trusted SSL certificates
                 --ssl-ciphers          Cipherlist containing SSL ciphers to use
                 --version              Display Ncat's version information and exit

           See the ncat(1) manpage for full options, descriptions and usage examples

nc常用命令實(shí)例

nc測(cè)試tcp和udp端口

# 測(cè)試tcp一般會(huì)想到使用telnet
telnet 192.168.12.10 22

# telnet不支持udp協(xié)議,所以我們可以使用nc抒巢,nc可以支持tcp也可以支持udp
yum install -y nc
nc -z -v 192.168.10.12 22 #tcp
nc -z -v -u 192.168.10.12 123 # udp

nc監(jiān)聽(tīng)端口和掃描連接端口

# 監(jiān)聽(tīng)端口
[root@localhost wangao]# nc -l 8888 -v
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Listening on :::8888
Ncat: Listening on 0.0.0.0:8888
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:56090.

# 連接端口
[root@localhost wangao]# nc -vz -w 5 127.0.0.1 8888
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 127.0.0.1:8888.
Ncat: 0 bytes sent, 0 bytes received in 0.01 seconds.

nc examples

EXAMPLES
       Connect to example.org on TCP port 8080.
           ncat example.org 8080

       Listen for connections on TCP port 8080.
           ncat -l 8080

       Redirect TCP port 8080 on the local machine to host on port 80.
           ncat --sh-exec "ncat example.org 80" -l 8080 --keep-open

       Bind to TCP port 8081 and attach /bin/bash for the world to access freely.
           ncat --exec "/bin/bash" -l 8081 --keep-open

       Bind a shell to TCP port 8081, limit access to hosts on a local network, and limit the
       maximum number of simultaneous connections to 3.
           ncat --exec "/bin/bash" --max-conns 3 --allow 192.168.0.0/24 -l 8081 --keep-open

       Connect to smtphost:25 through a SOCKS4 server on port 1080.
           ncat --proxy socks4host --proxy-type socks4 --proxy-auth user smtphost 25

       Create an HTTP proxy server on localhost port 8888.
           ncat -l --proxy-type http localhost 8888

       Send a file over TCP port 9899 from host2 (client) to host1 (server).
           HOST1$ ncat -l 9899 > outputfile

           HOST2$ ncat HOST1 9899 < inputfile

       Transfer in the other direction, turning Ncat into a “one file” server.
           HOST1$ ncat -l 9899 < inputfile

           HOST2$ ncat HOST1 9899 > outputfile

nc批量端口掃描腳本

方案1: 利用nc構(gòu)建簡(jiǎn)單的bash腳本

# 假如我們要監(jiān)控一堆指定的IP和端口贫贝,可新建一個(gè)文件(第1列為服務(wù)器IP,第2列為監(jiān)控的端口虐秦,中間用空格分隔)
[root@localhost ~]# vi ip-ports.txt
127.0.0.1 21
127.0.0.1 22
127.0.0.1 23

# 新建這樣一個(gè)腳本來(lái)批量檢測(cè)端口是否開(kāi)放平酿,成功會(huì)返回0值顯示ok凤优,失敗會(huì)返回1值顯示fail

[root@localhost ~]# vi ncports.sh
#!/bin/bash  

cat ip-ports.txt | while read line
do
  nc -w 10 -z $line > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    echo $line:ok
  else
    echo $line:failed
  fi
done

# 給腳本賦予可執(zhí)行權(quán)限悦陋,并執(zhí)行查看結(jié)果
[root@localhost ~]# chmod a+x ncports.sh
[root@localhost ~]# sh ncports.sh
127.0.0.1 21:failed
127.0.0.1 22:ok
127.0.0.1 23:failed

方案2: 利用nc或者nmap構(gòu)建復(fù)雜的bash腳本

# 創(chuàng)建配置文件
vim ports_list.cfg

#    IP        PROTOCOL(tcp/udp)        PORTS(1,2,3)
127.0.0.1      tcp                      21,22,23

# 創(chuàng)建腳本
vim scan_ports.sh

# 執(zhí)行腳本
[root@localhost ~]# ./scan_ports.sh
2020-10-08 12:03:31  Connection to 127.0.0.1 23 port [tcp/23] failed!
2020-10-08 12:03:31  Connection to 127.0.0.1 21 port [tcp/21] failed!
Hosts: 1 Ports: 3 Times: 0s

作用:批量端口掃描,可根據(jù)掃描主機(jī)的配置調(diào)整后臺(tái)掃描進(jìn)程數(shù)量(手動(dòng)執(zhí)行后根據(jù)統(tǒng)計(jì)的執(zhí)行時(shí)間調(diào)整腳本中關(guān)于進(jìn)程數(shù)量的參數(shù))筑辨,通過(guò)定時(shí)任務(wù)作為簡(jiǎn)單的服務(wù)監(jiān)控(可修改腳本添加其他報(bào)警功能俺驶,例如郵件等)

實(shí)現(xiàn):使用nc指令掃描端口,使用管道特性控制后臺(tái)掃描進(jìn)程數(shù)量

不足:僅僅對(duì)掃描端口狀態(tài)為down的信息做記錄棍辕,并沒(méi)有其他報(bào)警操作

使用:

  1. 需要提供包含被掃描主機(jī)的ip地址暮现、協(xié)議和端口號(hào)的配置文件(格式見(jiàn)演示或代碼專區(qū)注釋)
  2. 需要一個(gè)日志文件記錄端口down狀態(tài)信息。
  3. 配置和日志文件在腳本中定義楚昭,默認(rèn)為:ports_list.cfg 和 port_down.log
#!/bin/bash

# vim scan_ports.sh

# the conf_file, like this:
#------------------------------------------------------
#        IP       PROTOCOL(tcp/udp)     PORTS(1,2,3)  |
#                                                     |
#  192.168.2.250      tcp                21,22,23     |
#------------------------------------------------------

# config file
conf_file=ports_list.cfg
port_down_log=port_down.log

# number of backgroud processes
number_of_background_processes=1000

host_count=0
port_count=0

time_start=0
time_end=0

all_cfg_infor=$( grep -E -v '(^ *#|^$)' $conf_file )

# check nc
if ! rpm -q nc &>/dev/null; then
    yum install -y nc &>/dev/null
    [[ $? -ne 0 ]] && exit 1
fi

# print timestamp
function timestamp()
{
    echo -n "$(date +"%Y-%m-%d %H:%M:%S") "
}

# scan_ports main function
# host {tcp|udp} port
function scan_host_port()
{
    local this_protocol
    if [[ $2 == 'udp' ]]; then
        this_protocol='-u'
    else
        this_protocol=''
    fi
    if ! nc -z -w 1 $this_protocol $1 $3; then
        # can add other alert msg
        echo "$(timestamp) Connection to $1 $3 port [$2/$3] failed!" | tee -a $port_down_log
    # else
    #     echo "$(timestamp) Connection to $1 $3 port [$2/$3] ok!" | tee -a $port_down_log
    fi
}

sum_line_of_all_cfg_infor=$(echo "$all_cfg_infor" | wc -l)

# pipe operators
fifo_file=$(date +%s)
if mkfifo $fifo_file; then
    exec 46<>$fifo_file 
    rm -fr $fifo_file
else
    echo "Create fifo file failed !"
    exit 2
fi

# control function
time_start=$(date +%s)
for((count_n=1; count_n<=number_of_background_processes; count_n++))
do 
    echo >&46
done

echo -----------------------------$(timestamp)--------------------------- >>$port_down_log
for((line_num=1; line_num<=sum_line_of_all_cfg_infor; line_num++))
do
    
    line_infor=$( echo "$all_cfg_infor" | sed -n "${line_num}p" )
    line_ip=$( echo $line_infor | awk  '{print $1}' )
    line_protocol=$( echo $line_infor | awk '{print $2}' )
    # read line_ip line_protocol < <(echo $line_infor | awk  '{print $1,$2}')
    for this_port in $( echo $line_infor | awk '{print $3}' | tr ',' ' ')
    do
        # read pipe after port scan
        read -u46
        # put process into background for concurrency
        {
            scan_host_port $line_ip $line_protocol $this_port
            # make a write operation after pipe operator finished
            echo >&46
        } &
        let port_count++
    done
    let host_count++
done

wait
# release
exec 46>&-
exec 46<&-
time_end=$(date +%s)

echo Hosts: $host_count  Ports: $port_count  Times: $((time_end-time_start))s | tee -a $port_down_log

參考文章

10 useful ncat (nc) Command Examples for Linux Systems

nc命令用法舉例

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末栖袋,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子抚太,更是在濱河造成了極大的恐慌塘幅,老刑警劉巖昔案,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異电媳,居然都是意外死亡踏揣,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)匾乓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)捞稿,“玉大人,你說(shuō)我怎么就攤上這事拼缝∮榫郑” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵珍促,是天一觀的道長(zhǎng)铃辖。 經(jīng)常有香客問(wèn)我,道長(zhǎng)猪叙,這世上最難降的妖魔是什么娇斩? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任,我火速辦了婚禮穴翩,結(jié)果婚禮上犬第,老公的妹妹穿的比我還像新娘。我一直安慰自己芒帕,他們只是感情好歉嗓,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著背蟆,像睡著了一般鉴分。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上带膀,一...
    開(kāi)封第一講書(shū)人閱讀 48,970評(píng)論 1 284
  • 那天志珍,我揣著相機(jī)與錄音,去河邊找鬼垛叨。 笑死伦糯,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的嗽元。 我是一名探鬼主播敛纲,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼剂癌!你這毒婦竟也來(lái)了淤翔?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤佩谷,失蹤者是張志新(化名)和其女友劉穎旁壮,沒(méi)想到半個(gè)月后辞做,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡寡具,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年秤茅,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片童叠。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡框喳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出厦坛,到底是詐尸還是另有隱情五垮,我是刑警寧澤,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布杜秸,位于F島的核電站放仗,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏撬碟。R本人自食惡果不足惜诞挨,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望呢蛤。 院中可真熱鬧惶傻,春花似錦、人聲如沸其障。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)励翼。三九已至蜈敢,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間汽抚,已是汗流浹背抓狭。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留殊橙,地道東北人辐宾。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓狱从,卻偏偏與公主長(zhǎng)得像膨蛮,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子季研,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345