Python脚本开发求助:IP比对与批量Ping结果分类实现
思路指引与代码优化
核心步骤拆解
- 先把text2.txt里的所有IP加载到一个集合中,集合的查询效率远高于列表,适合快速做存在性检查
- 遍历text1.txt中的每个IP,判断是否在text2的IP集合内
- 对不在集合里的IP执行Ping操作,根据返回结果分流写入text3.txt(连通)和text4.txt(不通)
- 文件写入时用追加模式(
a),避免每次写入覆盖之前的内容
修正后的完整代码
#!/usr/bin/env python import os # 读取text2.txt的IP,存入集合 def load_ip_set(file_path): ip_set = set() with open(file_path, 'r') as f: for line in f: ip = line.strip() # 去掉换行符和首尾空格 if ip: # 跳过空行 ip_set.add(ip) return ip_set def main(): # 加载text2的IP集合 text2_ips = load_ip_set("text2.txt") # 批量打开文件,处理text1的每个IP with open("text1.txt", 'r') as text1, \ open("text3.txt", 'a') as up_file, \ open("text4.txt", 'a') as down_file: for line in text1: ip = line.strip() if not ip: continue # 跳过空行 if ip not in text2_ips: # 执行Ping,-W 2设置超时2秒,> /dev/null 2>&1屏蔽输出 response = os.system(f"ping -c 1 -W 2 {ip} > /dev/null 2>&1") if response == 0: up_file.write(f"{ip}\n") else: down_file.write(f"{ip}\n") if __name__ == "__main__": main()
原代码的问题说明
- 原代码用
open("output.txt","w"),w模式会清空文件后写入,导致最终只保留最后一个连通的IP,应该用a追加模式 - 未处理空行,可能会Ping空字符串导致错误
- 直接拼接命令字符串存在安全风险(若IP含特殊字符),新手阶段可先保证功能,后续可改用更安全的
subprocess.run:import subprocess result = subprocess.run(["ping", "-c", "1", "-W", "2", ip], capture_output=True) if result.returncode == 0: # IP连通逻辑
内容的提问来源于stack exchange,提问作者w8minute
相关产品推荐
相关产品推荐

