nc是linux网络工具的瑞士军刀,短小、灵活而又强大。在网络攻击中,也常用来进行数据包发送,文件传送以及反弹shell等等。

  • 命令参数
  • nc [-hlnruz][-g<网关...>][-G<指向器数目>][-i<延迟秒数>][-o<输出文件>][-p<通信端口>][-s<来源位址>][-v...][-w<超时秒数>][主机名称][通信端口...]

    -g<网关> 设置路由器跃程通信网关,最丢哦可设置8个。
    -G<指向器数目> 设置来源路由指向器,其数值为4的倍数。
    -h 在线帮助。
    -i<延迟秒数> 设置时间间隔,以便传送信息及扫描通信端口。
    -l 使用监听模式,管控传入的资料。
    -n 直接使用IP地址,而不通过域名服务器。
    -o<输出文件> 指定文件名称,把往来传输的数据以16进制字码倾倒成该文件保存。
    -p<通信端口> 设置本地主机使用的通信端口。
    -r 乱数指定本地与远端主机的通信端口。
    -s<来源位址> 设置本地主机送出数据包的IP地址。
    -u 使用UDP传输协议。
    -v 详细输出--用两个-v可得到更详细的内容
    -w<超时秒数> 设置等待连线的时间。
    -z 使用0输入/输出模式,只在扫描通信端口时使用。

  • tcp的通讯
  • A机器在1234端口建立监听

    root@localhost [~] nc -l 1234

    B机器连接A机器1234,并传递数据hello

    root@localhost [~] telnet 10.251.26.174 1234
    Trying 10.251.26.174...
    Connected to 10.251.26.174.
    Escape character is '^]'.
    hello

    此时,A机器便会收到hello消息,A与B机器已经建立了基于1234端口的tcp通讯。

  • udp发送请求
  • 发送成功与不成功都会返回信息,断开nc,可以使用ctl + C键。

    root@localhost [~] nc -u 127.0.0.1 5200
    ds
    nc: Write error: Connection refused
    ^C
    root@localhost [~]nc -u 127.0.0.1 5202
    hello
    world
  • 端口扫描
  • tcp端口扫描,输出成功连接端口

    root@localhost [~] nc -w 1 127.0.0.1 -z 20-100
    Connection to 127.0.0.1 22 port [tcp/ssh] succeeded!
    Connection to 127.0.0.1 80 port [tcp/http] succeeded!

    tcp端口扫描,输出详细信息

    root@localhost [~] nc -w 1 -v 127.0.0.1 -z 20-30
    nc: connect to 127.0.0.1 port 20 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 21 (tcp) failed: Connection refused
    Connection to 127.0.0.1 22 port [tcp/ssh] succeeded!
    nc: connect to 127.0.0.1 port 23 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 24 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 25 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 26 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 27 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 28 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 29 (tcp) failed: Connection refused
    nc: connect to 127.0.0.1 port 30 (tcp) failed: Connection refused

    udp端口扫描,输出成功连接端口

    root@localhost [~] nc -w 1 -u 127.0.0.1 -z 5000-6000
    Connection to 127.0.0.1 5201 port [udp/targus-getdata1] succeeded!
    Connection to 127.0.0.1 5202 port [udp/targus-getdata2] succeeded!
  • 拷贝文件
  • A机器在1234端口建立监听,得到内容存入到test.txt文件中,回车后进程会一直处于运行监听中。

    root@localhost [~] nc -l 1234 > test.txt

    B机器连接A机器1234,并传递文档test.txt。

    root@localhost [~] cat test.txt
    hello world
    root@localhost [~] nc 10.251.26.174 1234 < test.txt

    此时,A机器的nc进程结束,并会在当前目录建立一个text.txt,内容和B机器的一致。

    总结,nc命令使用场景非常多,这里不一一列举。有兴趣的可以自行研究,例如通过nc进行目录通讯,执行shell。