
Python远程IP地址连通性测试
本文提供一种使用Python验证远程IP地址连通性的方法,并处理不同网络状况:正常连接、间歇性连接和完全无法连接。 该方法利用系统自带的ping命令(或tcping,需提前安装),避免了第三方模块可能存在的兼容性问题。
前提条件:
确保您的系统已安装ping命令(通常默认安装)。如果需要更精确的测试,建议安装tcping。
立即学习“Python免费学习笔记(深入)”;
代码示例:
import os
import subprocess
def check_ip_connectivity(ip_address, use_tcping=False):
"""
验证远程IP地址的连通性。
Args:
ip_address: 要验证的IP地址。
use_tcping: 是否使用tcping命令 (默认False, 使用ping)。
Returns:
字典,包含连通性信息:
- connected: 布尔值,指示是否连接。
- packet_loss: 丢包率 (如果连接)。
- avg_latency: 平均延迟 (如果连接)。
或 None (如果命令执行失败)。
"""
command = f"ping -c 3 {ip_address}" if not use_tcping else f"tcping -c 3 {ip_address}"
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True, check=True)
output = result.stdout
if "packet loss" in output.lower() or "unreachable" in output.lower():
connected = False
packet_loss = None
avg_latency = None
else:
connected = True
lines = output.splitlines()
for line in lines:
if "packet loss" in line.lower():
packet_loss = float(line.split(',')[2].split('%')[0])
if "avg" in line.lower():
avg_latency = float(line.split('/')[-2])
return {"connected": connected, "packet_loss": packet_loss, "avg_latency": avg_latency}
except subprocess.CalledProcessError as e:
print(f"命令执行失败: {e}")
return None
except Exception as e:
print(f"发生错误: {e}")
return None
ip_address = "8.8.8.8" # Google Public DNS
result = check_ip_connectivity(ip_address)
if result:
if result["connected"]:
print(f"IP {ip_address} 连接成功:")
if result["packet_loss"] is not None:
print(f" 丢包率: {result['packet_loss']:.2f}%")
if result["avg_latency"] is not None:
print(f" 平均延迟: {result['avg_latency']:.2f}ms")
else:
print(f"IP {ip_address} 连接失败")
此代码使用subprocess模块更安全地执行系统命令,并对输出进行更清晰的解析,提供更详细的连接信息。 它还增加了use_tcping参数,允许用户选择使用tcping命令进行更精确的测试。 错误处理也更加完善。










