Python 3.10从JSON提取IP转列表并批量Ping的实现方法
问题分析与解决方案
你的代码存在两个核心问题,同时我会给出提取IP列表并批量Ping的正确实现:
核心问题说明
Ping语句缩进错误
你第一段代码中的Host = (router['host'])和ping(Host, verbose=True)没有缩进,不在for循环内部。这导致循环结束后,只会使用最后一个路由器的IP执行Ping,而非逐个遍历所有IP。JSON读取方法误用
第二段测试代码里的json.loads('credentials.json')完全错误:json.load()才是读取文件对象加载JSON数据的正确方式json.loads()用于解析JSON格式的字符串,不能直接传入文件名json.dumps()是将Python对象转为JSON字符串,和读取文件的需求无关
正确实现步骤
1. 提取IP地址到独立列表
用列表推导式可以快速从JSON数据中提取所有IP:
import json with open('credentials.json', 'r') as f: hosts = json.load(f) # 提取所有host字段到IP列表 ip_list = [item['host'] for item in hosts] print(ip_list) # 输出: ['10.1.2.13', '10.0.1.13']
2. 批量Ping所有IP
将Ping操作放入for循环内部,逐个处理每个IP:
import json from pythonping import ping with open('credentials.json', 'r') as f: hosts = json.load(f) # 遍历每个路由器信息,附带设备名称Ping for router in hosts: ip = router['host'] print(f"\n正在Ping {router['name']} ({ip})...") ping(ip, verbose=True)
或者直接用提取好的IP列表遍历:
import json from pythonping import ping with open('credentials.json', 'r') as f: hosts = json.load(f) ip_list = [item['host'] for item in hosts] for ip in ip_list: print(f"\n正在Ping {ip}...") ping(ip, verbose=True)
额外优化:添加异常处理
可以加入异常捕获,避免单个IP Ping失败导致程序中断:
import json from pythonping import ping from pythonping.executor import PingError with open('credentials.json', 'r') as f: hosts = json.load(f) for router in hosts: ip = router['host'] print(f"\n正在Ping {router['name']} ({ip})...") try: ping(ip, verbose=True) except PingError as e: print(f"Ping {ip}失败: {str(e)}")
内容的提问来源于stack exchange,提问作者AndyC
相关产品推荐
相关产品推荐

