如何用Python读取CSV的网段子网掩码批量ping IP并输出结果
实现方案
核心依赖说明
Python 3.3及以上版本自带ipaddress标准库,可直接完成网段计算、IP遍历,无需手动实现掩码换算逻辑。subprocess标准库用于调用系统ping命令,准确率远高于第三方模拟ping实现。
完整脚本实现
import csv import subprocess import ipaddress from concurrent.futures import ThreadPoolExecutor, as_completed # 配置项 MAX_WORKERS = 50 # 并发ping的线程数,可根据网络环境调整 PING_TIMEOUT = 2 # 单个IP的ping超时时间(秒) def ping_ip(ip_str): """校验单个IP是否可达,返回(IP, 可达状态布尔值)""" import platform # 适配Windows和类Unix系统的ping参数 count_param = '-n' if platform.system().lower() == 'windows' else '-c' wait_param = '-w' if platform.system().lower() == 'windows' else '-W' timeout_val = str(PING_TIMEOUT * 1000) if platform.system().lower() == 'windows' else str(PING_TIMEOUT) command = ['ping', count_param, '1', wait_param, timeout_val, ip_str] # 执行ping,返回码为0表示可达 result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return (ip_str, result.returncode == 0) if __name__ == "__main__": # 1. 读取csv文件 with open('files.csv', 'r', encoding='utf-8') as f: reader = csv.reader(f) subnet_list = [row for row in reader if len(row) == 2] for network_str, netmask_str in subnet_list: try: # 2. 计算子网,自动校验网段+掩码的合法性 subnet = ipaddress.IPv4Network(f"{network_str}/{netmask_str}", strict=False) output_file = f"{network_str}.txt" print(f"正在处理子网:{subnet},结果将写入{output_file}") # 3. 多线程并发ping所有可用IP(自动跳过网络地址和广播地址) usable_ips = [str(ip) for ip in subnet.hosts()] ping_results = [] with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [executor.submit(ping_ip, ip) for ip in usable_ips] for future in as_completed(futures): ping_results.append(future.result()) # 4. 结果按IP顺序写入文件 ping_results.sort(key=lambda x: ipaddress.IPv4Address(x[0])) with open(output_file, 'w', encoding='utf-8') as f: f.write(f"子网:{subnet}\n") f.write(f"总可用IP数:{len(usable_ips)}\n\n") f.write("可达IP列表:\n") for ip, is_up in ping_results: if is_up: f.write(f"{ip}\n") f.write("\n不可达IP列表:\n") for ip, is_up in ping_results: if not is_up: f.write(f"{ip}\n") except Exception as e: print(f"处理网段{network_str}/{netmask_str}出错:{str(e)}")
关键逻辑说明
- 子网计算:调用
ipaddress.IPv4Network传入网段/掩码格式的字符串,strict=False参数允许输入的网段不是严格对齐的网络地址,会自动修正为正确的网络地址。subnet.hosts()方法直接返回所有排除了网络地址、广播地址的可用IP,无需自己遍历生成。 - ping实现:调用系统原生ping命令,适配Windows和Linux/macOS系统,避免原始套接字需要管理员权限的问题。
- 多线程优化:默认50并发,相比单线程串行ping,执行速度提升几十倍,可根据自己的网络带宽调整
MAX_WORKERS参数。
使用注意
- 确保
files.csv和脚本放在同一目录下,csv不要加表头,每行严格为网段,子网掩码格式 - Windows环境下运行如果出现编码错误,可把文件打开的
encoding='utf-8'改为encoding='gbk'
内容的提问来源于stack exchange,提问作者user3847270
相关产品推荐
相关产品推荐

