前言
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的作用:
- 實(shí)現(xiàn)任意TCP/UDP端口的偵聽(tīng)梦湘,nc可以作為server以TCP或UDP方式偵聽(tīng)指定端口
- 端口的掃描,nc可以作為client發(fā)起TCP或UDP連接
- 機(jī)器之間傳輸文件
- 機(jī)器之間網(wǎng)絡(luò)測(cè)速
nc的控制參數(shù)不少件甥,常用的幾個(gè)參數(shù)如下所列:
- -l
用于指定nc將處于偵聽(tīng)模式捌议。指定該參數(shù),則意味著nc被當(dāng)作server引有,偵聽(tīng)并接受連接瓣颅,而非向其它地址發(fā)起連接。
- -p <port>
暫未用到(老版本的nc可能需要在端口號(hào)前加-p參數(shù))
- -s
指定發(fā)送數(shù)據(jù)的源IP地址譬正,適用于多網(wǎng)卡機(jī)
- -u
指定nc使用UDP協(xié)議宫补,默認(rèn)為T(mén)CP
- -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)警操作
使用:
- 需要提供包含被掃描主機(jī)的ip地址暮现、協(xié)議和端口號(hào)的配置文件(格式見(jiàn)演示或代碼專區(qū)注釋)
- 需要一個(gè)日志文件記錄端口down狀態(tài)信息。
- 配置和日志文件在腳本中定義楚昭,默認(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