如何用Python 3.1从D盘TXT文件批量Ping多个IP地址?
适配Python3.1的IP批量Ping检测方案
代码实现
import requests import os import time # 适配Python3.1的schedule版本:pip install schedule==1.1.0 import schedule def notifyNetwork(message): token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" uri = "https://notify-api.line.me/api/notify" header = {"Authorization": "Bearer " + token} msg = {"message": "TEST \n" + message} resp = requests.post(uri, headers=header, data=msg) def checkNetwork(hostname): # Windows系统ping命令:发送1个包,超时1秒;Linux/macOS替换为 "ping -c 1 -W 1 {0}".format(hostname) ping_cmd = "ping -n 1 -w 1 {0}".format(hostname) response = os.system(ping_cmd) # Windows下ping成功退出码为0,失败为非0 return response == 0 def load_hosts_from_txt(file_path): hosts = [] try: with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() # 跳过空行和注释行(以#开头) if not line or line.startswith('#'): continue # 按逗号分隔IP和主机名,自动处理空格 parts = line.split(',') ip = parts[0].strip() # 若未指定主机名,默认使用IP name = parts[1].strip() if len(parts) >= 2 else ip # 初始状态设为False(离线) hosts.append([ip, name, False]) return hosts except FileNotFoundError: print("错误:未找到文件 {0}".format(file_path)) return [] except Exception as e: print("读取文件出错:{0}".format(str(e))) return [] # 从D盘指定文件读取IP列表,路径请根据实际修改 hostname = load_hosts_from_txt("D:/ip_list.txt") # 若无可用主机,直接退出 if not hostname: print("没有可检测的主机,程序退出") exit() def monitor_network(): for index, test_host in enumerate(hostname): currentStatus = checkNetwork(test_host[0]) previousStatus = test_host[2] if currentStatus == previousStatus: print("[{0}] 状态无变化,不发送通知".format(test_host[0])) else: hostname[index][2] = currentStatus statusNetwork = 'UP' if currentStatus else 'Down' message = "IP : {0}\nName : {1}\n状态: {2}".format(test_host[0], test_host[1], statusNetwork) notifyNetwork(message) print("[{0}] 状态变更为{1},已发送Line通知".format(test_host[0], statusNetwork)) # 单主机检测间隔5秒,避免检测过于频繁 time.sleep(5) # 本轮检测完成后输出所有主机状态 print("\n本轮检测完成,当前主机状态:") for host in hostname: print("{0}({1}):{2}".format(host[1], host[0], '在线' if host[2] else '离线')) print("----------------------------------------") # 可选:设置定时检测任务(例如每10分钟执行一次) # schedule.every(10).minutes.do(monitor_network) # 持续循环检测(若使用schedule定时任务,注释下面的monitor_network(),保留schedule.run_pending()) while True: monitor_network() # schedule.run_pending() # 两轮检测间隔30秒,可根据需求调整 time.sleep(30)
关键说明
TXT文件格式要求(示例路径:
D:/ip_list.txt):# 注释行(会被忽略) 192.168.1.200,EU (SERVER) 10.0.0.1,US (SERVER) 172.16.0.5,Local Router- 每行格式:
IP地址,主机名称,主机名称可选 - 空行和以
#开头的行会被自动跳过
- 每行格式:
Python3.1兼容性处理:
- 替换了Python3.6+才支持的f-string,改用
.format()方法 - 指定兼容Python3.1的第三方库版本:
- 安装requests:
pip install requests==2.27.1 - 安装schedule(若使用定时任务):
pip install schedule==1.1.0
- 安装requests:
- 替换了Python3.6+才支持的f-string,改用
Ping命令适配:
- 代码默认适配Windows系统,若使用Linux/macOS,请修改
checkNetwork函数中的ping_cmd为:ping_cmd = "ping -c 1 -W 1 {0}".format(hostname)
- 代码默认适配Windows系统,若使用Linux/macOS,请修改
功能保留:
- 保留原代码的Line Notify通知功能,仅在主机状态变化时发送通知
- 自动记录并对比上一次检测状态,避免重复通知
内容的提问来源于stack exchange,提问作者DarkZone
相关产品推荐
相关产品推荐

