在Linux系统中,测试端口是否连通有多种方法,以下是常用的几种方式:
telnet
命令bash
telnet <IP或域名> <端口号>
- 示例:测试 example.com
的 80
端口
bash
telnet example.com 80
- 结果说明:
- 连接成功:显示 Connected to...
或空白光标(表示端口开放)。
- 连接失败:显示 Connection refused
或超时(端口关闭或防火墙拦截)。
注意:若系统未安装
telnet
,可通过以下命令安装:sudo apt install telnet # Debian/Ubuntu sudo yum install telnet # CentOS/RHEL
nc
(netcat) 命令bash
nc -zv <IP或域名> <端口号>
- 参数说明:
- -z
:扫描模式(不发送数据)。
- -v
:显示详细输出。
- 示例:测试 192.168.1.1
的 22
端口
bash
nc -zv 192.168.1.1 22
- 结果说明:
- 成功:Connection to <IP> <port> [tcp/*] succeeded!
- 失败:显示超时或拒绝连接。
安装
netcat
:sudo apt install netcat # Debian/Ubuntu sudo yum install nc # CentOS/RHEL
curl
测试HTTP/HTTPS端口bash
curl -v http(s)://<IP或域名>:<端口>
- 示例:测试 https://example.com:443
bash
curl -v https://example.com:443
- 结果说明:
- 成功:返回HTTP响应头(如 HTTP/1.1 200 OK
)。
- 失败:显示 Failed to connect
或超时。
nmap
扫描端口bash
nmap -p <端口号> <IP或域名>
- 示例:扫描 example.com
的 80
端口
bash
nmap -p 80 example.com
- 结果说明:
- 开放:<port> open
- 关闭:<port> closed
或未列出。
安装
nmap
:sudo apt install nmap # Debian/Ubuntu sudo yum install nmap # CentOS/RHEL
ss
或 netstat
检查本地监听端口bash
ss -tulnp | grep <端口号>
或
netstat -tulnp | grep <端口号> # 较旧系统
22
端口
bash
ss -tulnp | grep 22
ping
结合端口测试(ICMP+端口)telnet
/nc
测试:
bash
ping <IP或域名> && nc -zv <IP或域名> <端口>
连接失败的可能原因:
iptables
/ufw
/云平台安全组)。ss
或 netstat
确认)。超时但端口可能开放:
-w
参数设置超时时间(如 nc -zv -w 3 <IP> <端口>
)。根据场景选择合适的方法。简单测试推荐 telnet
或 nc
,详细分析可用 nmap
。