nc -zv
实用示例
示例 1:测试单个 TCP 端口(最常见)
目标: 检查主机 webserver.example.com
上的 80
端口 (HTTP) 是否开放。
nc -zv webserver.example.com 80
成功输出:
Connection to webserver.example.com (192.168.1.10) 80 port [tcp/http] succeeded!
失败输出(端口无服务):
nc: connect to webserver.example.com port 80 (tcp) failed: Connection refused
失败输出(网络不通/防火墙阻断):
nc: connect to webserver.example.com port 80 (tcp) timed out: Operation now in progress
示例 2:测试单个 UDP 端口
目标: 检查 DNS 服务器 dns.google
的 53
端口 (DNS) 是否响应 UDP 请求。
nc -zvu dns.google 53
成功输出:
Connection to dns.google (8.8.8.8) 53 port [udp/domain] succeeded!
失败输出(UDP 特性注意): UDP 是无连接的,succeeded
只表示数据包成功发送到目标端口,并不保证端口一定有服务监听或会响应。如果端口完全没有服务,通常不会收到错误,命令可能直接返回成功或超时。如果网络不通,会报告类似 TCP 的超时或路由错误。
示例 3:测试指定 IP 和端口范围 (批量扫描)
目标: 快速扫描主机 192.168.1.100
上几个常用端口 (22
SSH, 80
HTTP, 443
HTTPS) 的状态。
nc -zv 192.168.1.100 22 80 443
输出:
Connection to 192.168.1.100 22 port [tcp/ssh] succeeded!
Connection to 192.168.1.100 80 port [tcp/http] succeeded!
nc: connect to 192.168.1.100 port 443 (tcp) failed: Connection refused
明确显示了 22 和 80 开放,443 被拒绝(可能无服务或防火墙阻断)。
示例 4:结合超时参数 (避免长时间等待)
目标: 测试一个可能不通或响应慢的端口 (8080
),设置 3 秒超时。
nc -zv -w 3 slowserver.example.com 8080
-w 3
: 设置连接超时时间为 3 秒。
输出(如果 3 秒内未连接成功):
nc: connect to slowserver.example.com port 8080 (tcp) timed out: Operation now in progress
示例 5:测试域名解析 + 端口 (验证 DNS 和网络)
目标: 检查能否解析 api.service.com
并连接其 443
端口。
nc -zv api.service.com 443
成功输出:
Connection to api.service.com (203.0.113.45) 443 port [tcp/https] succeeded!
成功输出包含了解析到的 IP 地址 (203.0.113.45) 和端口状态。
失败输出(域名解析失败):
nc: getaddrinfo for api.service.com port 443: Name or service not known
失败输出(能解析但端口不通):
nc: connect to api.service.com (203.0.113.45) port 443 (tcp) failed: Connection timed out
nc -zv
输出格式不同
有时我们输入 nc -zv 172.16.7.78 80
,得到的确实下面这种形式的输出:
Ncat: Version 7.50 (https://nmap.org/ncat) # 这是 Nmap 项目的 Ncat 工具
Ncat: Connected to 172.16.7.78:80. # 关键信息:连接成功!
Ncat: 0 bytes sent, 0 bytes received in 0.06 seconds. # 零数据传输统计
这说明当前使用的 Ncat
是来自 Nmap 项目的增强版 Netcat,而不是传统的 BSD 或 GNU 版本的。