素槿
Published on 2025-08-22 / 3 Visits
0

NC(netcat的使用)

1.简介

网络工具中的瑞士军刀。

需要注意的是nc有两个版本,全功能版有-c和-e参数,而阉割版没有。

安装:

# apt install netcat

查看帮助:

$ nc -h

2.Telenet(远程登录服务)功能

nc可以检测相应的IP和端口上有没有开启某项服务。

# nc -nv 172.30.18.253 22
Connection to 172.30.18.253 22 port [tcp/*] succeeded!
SSH-2.0-OpenSSH

# nc -nv 172.17.0.3 22
nc: connect to 172.17.0.3 port 22 (tcp) failed: Connection refused

# nc -nv 172.30.18.253 80
nc: connect to 172.30.18.253 port 80 (tcp) failed: Connection refused

通过以上操作,可以检测对应主机有没有在22端口开启ssh或开启80端口。

  • -n 跟IP地址
  • -v 显示详细信息

3.文本传输功能

host1充当服务器:

# nc -l -p 8888
  • -l 进入监听模式
  • -p 指定监听端口

host2充当客户端进行连接,并发送消息:

# nc -nv 172.17.0.3 8888
Connection to 172.17.0.3 8888 port [tcp/*] succeeded!
123

host1接收到消息:

# nc -l -p 8888
123

host1发送消息 456:

# nc -l -p 8888
123
456

host2接受到信息:

# nc -nv 172.17.0.3 8888
Connection to 172.17.0.3 8888 port [tcp/*] succeeded!
123
456

host2可以向服务器端发送任意文本信息:

$ cat xxx.txt | nc -nv 172.17.0.3 8888

UDP端口:

# nc -lu 8888    // server

# nc -nvu 172.17.0.2 8888		// client

4.文件传输功能

(1)客户端向服务端传输

服务器端将监听内容保存为1.txt

# nc -l -p 8888 > 1.txt

客户端传输文件,如xxx.txt

# nc -nv 172.17.0.2 8888 < xxx.txt -q 1
Connection to 172.17.0.2 8888 port [tcp/*] succeeded!
  • -q 1 传递结束后1s退出

可以传输其他类型的文件,不一定是文本文件。

(2)服务器端向客户端传输文件

服务器端传输任意文件:

# nc -l -p 8888 < 1.txt

客户端接收文件:

# nc -nv 172.17.0.2 8888 > 2.txt           
Connection to 172.17.0.2 8888 port [tcp/*] succeeded!
^C
root@84ce80b48c2a:~# cat 2.txt 
asndkasadsado

(3)传输目录

传输目录和传输文件一样,只需要先将文件用tar打包即可。

5.端口扫描

NC还可以对目标主机进行端口扫描

(1)扫描tcp端口

# nc -vz 172.17.0.2 1-1024
nc: connect to 172.17.0.2 port 21 (tcp) failed: Connection refused
Connection to 172.17.0.2 22 port [tcp/*] succeeded!
nc: connect to 172.17.0.2 port 79 (tcp) failed: Connection refused
Connection to 172.17.0.2 80 port [tcp/*] succeeded!
  • -z 使用扫描模式

(2)扫描UDP端口

# nc -vzu 172.17.0.2 1-1024

6.克隆硬盘

接收端先监听,并设置克隆硬盘:

# nc -l -p 8888 | dd of=/dev/sdc

目标服务器,克隆本地sda硬盘:

# dd if=/dev/sda | nc -nv 172.17.0.2 8888 -q 1

7.远程控制

服务器端:

# mkfifo /tmp/f
# cat /tmp/f | /bin/bash -i 2>&1 | nc -l 8888 > /tmp/f

客户端连接之后可以直接输入shell指令,效果类似ssh:

root@84ce80b48c2a:~# nc 172.17.0.2 8888
root@be06bac03f87:/# ls
......

8.请求网站

手动使用HTTP协议请求百度。

# printf "GET / HTTP/1.0\r\n\r\n" | nc baidu.com 80
HTTP/1.1 200 OK
Date: Wed, 06 Jan 2021 05:51:36 GMT
Server: Apache
Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
ETag: "51-47cf7e6ee8400"
Accept-Ranges: bytes
Content-Length: 81
Cache-Control: max-age=86400
Expires: Thu, 07 Jan 2021 05:51:36 GMT
Connection: Close
Content-Type: text/html

<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>