如何用ping命令测试服务器端口?网络连通性检查方法分享
- 云服务器
- 2026-02-08
- 3792
import socket import time def check_port(host, port, timeout=2): """ 检测指定主机和端口的开放状态 :param host: 目标主机IP或域名 :param port: 目标端口 :param timeout: 连接超时时间(秒) :return: (状态, 延迟毫秒数) 状态为字符串描述 """ start_time = time.time() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) try: s.connect((host, port)) elapsed = int((time.time() - start_time) * 1000) return f" 端口 {port} 开放", elapsed except socket.timeout: return f" 端口 {port} 连接超时", None except ConnectionRefusedError: return f" 端口 {port} 拒绝连接", None except socket.gaierror: return f" 主机名解析失败", None except Exception as e: return f"️ 未知错误: {str(e)}", None finally: s.close() if __name__ == "__main__": # 配置检测参数 host = "example.com" # 目标主机 ports = [80, 443, 22, 3389] # 要检测的端口列表 print(f"开始检测 {host} 的端口状态...n") for port in ports: result, latency = check_port(host, port) if latency is not None: print(f"{result} | 延迟: {latency}ms") else: print(result) print("n检测完成")
功能说明:
- TCP 连接检测:使用 socket 尝试建立 TCP 连接
- 多端口支持:可一次性检测多个端口状态
- 详细状态反馈:
- 端口开放(成功建立连接)
- 端口关闭(连接被拒绝)
- 连接超时(可能被防火墙拦截)
- 主机名解析失败
- ️ 其他未知错误
- 延迟测量:显示成功连接的网络延迟(毫秒)
使用示例:
# 检测百度的常用端口 host = "www.baidu.com" ports = [80, 443, 21, 8080]
输出示例:
开始检测 www.baidu.com 的端口状态... 端口 80 开放 | 延迟: 32ms 端口 443 开放 | 延迟: 28ms 端口 21 拒绝连接 端口 8080 拒绝连接 检测完成
注意事项:
- 需要目标服务器响应 TCP 握手(ICMP ping 不可用)
- 可能被防火墙干扰(超时不代表端口关闭)
- 对 UDP 端口无效(需使用其他技术)
- 频繁扫描可能触发安全机制
提示:对于批量扫描需求,可结合 concurrent.futures 模块实现多线程加速检测。


