前言

nc是netcat的简写,有着网络界的瑞士军刀美誉。因为它短小精悍、功能实用,被设计为一个简单、可靠的网络工具。比如大家很熟悉使用telnet测试tcp端口,而nc可以支持测试linux的tcp和udp端口,而且也经常被用于端口扫描,甚至把nc作为server以TCP或UDP方式侦听指定端口做简单的模拟测试。

更新历史

2020年10月07日 - 初稿

阅读原文 - https://wsgzao.github.io/post/nc/


nc简介

ncat 或者说 nc 是一款功能类似 cat 的工具,但是是用于网络的。它是一款拥有多种功能的 CLI 工具,可以用来在网络上读、写以及重定向数据。 它被设计成可以被脚本或其他程序调用的可靠的后端工具。同时由于它能创建任意所需的连接,因此也是一个很好的网络调试工具。

ncat/nc 既是一个端口扫描工具,也是一款安全工具,还能是一款监测工具,甚至可以做为一个简单的 TCP 代理。 由于有这么多的功能,它被誉为是网络界的瑞士军刀。 这是每个系统管理员都应该知道并且掌握它。

在大多数 Debian 发行版中,nc 是默认可用的,它会在安装系统的过程中自动被安装。 但是在 CentOS 7 / RHEL 7 的最小化安装中,nc 并不会默认被安装。 你需要用下列命令手工安装。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 安装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

# 执行nc或者nmap-ncat安装都可以
yum install nmap-ncat -y

# 我们通过 ll 命令查看 nc 命令, 老版本对应的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. 实现任意TCP/UDP端口的侦听,nc可以作为server以TCP或UDP方式侦听指定端口
  2. 端口的扫描,nc可以作为client发起TCP或UDP连接
  3. 机器之间传输文件
  4. 机器之间网络测速

nc的控制参数不少,常用的几个参数如下所列:

  1. -l

用于指定nc将处于侦听模式。指定该参数,则意味着nc被当作server,侦听并接受连接,而非向其它地址发起连接。

  1. -p

暂未用到(老版本的nc可能需要在端口号前加-p参数)

  1. -s

指定发送数据的源IP地址,适用于多网卡机

  1. -u

指定nc使用UDP协议,默认为TCP

  1. -v

输出交互或出错信息,新手调试时尤为有用

6)-w

超时秒数,后面跟数字

7)-z

表示zero,表示扫描时不发送任何数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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常用命令实例

nc测试tcp和udp端口

1
2
3
4
5
6
7
# 测试tcp一般会想到使用telnet
telnet 192.168.12.10 22

# telnet不支持udp协议,所以我们可以使用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监听端口和扫描连接端口

1
2
3
4
5
6
7
8
9
10
11
12
13
# 监听端口
[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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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构建简单的bash脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 假如我们要监控一堆指定的IP和端口,可新建一个文件(第1列为服务器IP,第2列为监控的端口,中间用空格分隔)
[root@localhost ~]# vi ip-ports.txt
127.0.0.1 21
127.0.0.1 22
127.0.0.1 23

# 新建这样一个脚本来批量检测端口是否开放,成功会返回0值显示ok,失败会返回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

# 给脚本赋予可执行权限,并执行查看结果
[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构建复杂的bash脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建配置文件
vim ports_list.cfg

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

# 创建脚本
vim scan_ports.sh

# 执行脚本
[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

作用:批量端口扫描,可根据扫描主机的配置调整后台扫描进程数量(手动执行后根据统计的执行时间调整脚本中关于进程数量的参数),通过定时任务作为简单的服务监控(可修改脚本添加其他报警功能,例如邮件等)

实现:使用nc指令扫描端口,使用管道特性控制后台扫描进程数量

不足:仅仅对扫描端口状态为down的信息做记录,并没有其他报警操作

使用:

  1. 需要提供包含被扫描主机的ip地址、协议和端口号的配置文件(格式见演示或代码专区注释)
  2. 需要一个日志文件记录端口down状态信息。
  3. 配置和日志文件在脚本中定义,默认为:ports_list.cfg 和 port_down.log
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/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命令用法举例

文章目录
  1. 1. 前言
  2. 2. 更新历史
  3. 3. nc简介
  4. 4. nc常用命令
  5. 5. nc常用命令实例
    1. 5.1. nc测试tcp和udp端口
    2. 5.2. nc监听端口和扫描连接端口
    3. 5.3. nc examples
    4. 5.4. nc批量端口扫描脚本
  6. 6. 参考文章