nc 命令使用小结 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
wsgzao
V2EX    Linux

nc 命令使用小结

  •  
  •   wsgzao
    wsgzao 2020-10-27 11:30:00 +08:00 1452 次点击
    这是一个创建于 1876 天前的主题,其中的信息可能已经有所发展或是发生改变。

    前言

    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 并不会默认被安装。 你需要用下列命令手工安装。

    # 安装 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 <port>

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

    1. -s

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

    1. -u

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

    1. -v

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

    6 )-w

    超时秒数,后面跟数字

    7 )-z

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

    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 端口

    # 测试 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 监听端口和扫描连接端口

    # 监听端 [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 构建简单的 bash 脚本

    # 假如我们要监控一堆指定的 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 脚本

    # 创建配置文件 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
    #!/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 命令用法举例

    2 条回复    2020-10-27 15:38:45 +08:00
    cubecube
        1
    cubecube  
       2020-10-27 11:31:54 +08:00
    nc 最 nc 的一点就是,不同系统上,各个版本有巨大的区别,nc ncat netcat 都可能不一样。所以每次还得根据系统,man 一下
    zhangysh1995
        2
    zhangysh1995  
       2020-10-27 15:38:45 +08:00
    友情提示各位 v 友:
    第二十七条 任何个人和组织不得从事非法侵入他人网络、干扰他人网络正常功能、窃取网络数据等危害网络安全的活动;不得提供专门用于从事侵入网络、干扰网络正常功能及防护措施、窃取网络数据等危害网络安全活动的程序、工具;明知他人从事危害网络安全的活动的,不得为其提供技术支持、广告推广、支付结算等帮助。
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     4505 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 30ms UTC 10:00 PVG 18:00 LAX 02:00 JFK 05:00
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86