求可从文本中提取IP地址并对IP执行ping操作的Python程序
从文本解析IP并执行Ping操作的Python程序
实现逻辑
- 通过正则表达式匹配所有符合标准IPv4格式的地址,自动过滤非IP内容
- 适配Windows、Linux、macOS三类系统的ping命令参数差异
- 批量执行ping检测,输出每个IP的连通性结果
完整代码
import re import subprocess import platform def extract_ips_from_text(text: str) -> list: # 匹配标准IPv4地址的正则表达式 ip_pattern = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b' return re.findall(ip_pattern, text) def ping_ip(ip: str, count: int = 2, timeout: int = 3) -> bool: # 根据操作系统选择ping命令参数 os_type = platform.system().lower() if os_type == 'windows': command = ['ping', '-n', str(count), '-w', str(timeout * 1000), ip] else: command = ['ping', '-c', str(count), '-W', str(timeout), ip] # 执行ping命令,返回是否连通 try: result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return result.returncode == 0 except Exception as e: print(f"检测IP {ip} 时出错: {str(e)}") return False if __name__ == '__main__': # 读取待解析的文本文件,可自行修改文件路径 with open('ip_text.txt', 'r', encoding='utf-8') as f: raw_text = f.read() extracted_ips = extract_ips_from_text(raw_text) # 去重处理 extracted_ips = list(set(extracted_ips)) if not extracted_ips: print("未从文本中解析到任何IP地址") exit() print(f"成功解析到 {len(extracted_ips)} 个IP地址:{', '.join(extracted_ips)}") print("\n开始执行Ping检测:") for ip in extracted_ips: status = "连通" if ping_ip(ip) else "不连通" print(f"IP {ip} 检测结果:{status}")
使用说明
- 将待解析的文本内容保存为
ip_text.txt,和脚本放在同一目录下 - 脚本默认发送2个ping包、超时时间设为3秒,可按需修改
ping_ip的传参 - 提取到的IP会自动去重,避免重复检测
内容的提问来源于stack exchange,提问作者kaydee
相关产品推荐
相关产品推荐

