You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改多IP批量Ping代码适配逗号分隔的输入格式?

解决批量Ping逗号分隔IP/域名的问题

现有Python批量Ping代码仅支持处理每行单个IP或域名的输入文件(格式示例如下),现在需要修改代码以适配每行包含多个逗号分隔IP/域名的场景。

单条每行输入格式:

8.8.8.8
www.google.com
www.yahoo.com
www.microsoft.com

多条逗号分隔输入格式:

8.8.8.8, www.google.com
www.yahoo.com,www.microsoft.com

原代码(仅支持单条每行格式)

import subprocess
import threading
import time
import re

timestr = time.strftime("%Y-%m-%d %H%M%S")
timesec = time.strftime("%Y-%m-%d%H:%M:%S")

raw_list = []
def ping(host):
    results_file = open("results_bng_" + str(timestr) + ".txt", "a")
    p = subprocess.Popen(["ping", host, "-n", "5"], shell=True, universal_newlines=True, stdout=subprocess.PIPE)
    response = p.communicate()[0]
    for i in response.split("\n"):
            para =i.split("=")
            # print(para)
            try:
                if para[0].strip() =="Minimum":
                    latency =para[3].strip()
                    print(latency)
                    latfin = re.findall('\d+', latency)
                    latfin1 = latfin[0]
            except:
                print("time run")

    if "Received = 1" and "Approximate" in response:
        print(f"UP {host} Ping Successful")
        results_file.write(f"{host},UP,{latfin1},{timesec}"+ "\n")
    else:
        print(f"Down {host} Ping Unsuccessful")
        results_file.write(f"{host},Down,0,{timesec}" + "\n")
    results_file.close()

with open(r'bng.txt', "r") as server_list_file:
    hosts = server_list_file.read()
    hosts_list =hosts.split('\n')
num_threads = 1
number = 0
while number< len(hosts_list):
    # print(number)
    for i in range(num_threads):
        t = threading.Thread(target=ping, args=(hosts_list[number+i],))
        t.start()
    t.join()
    number = number +1

修改后的代码(兼容两种输入格式)

import subprocess
import threading
import time
import re

timestr = time.strftime("%Y-%m-%d %H%M%S")
timesec = time.strftime("%Y-%m-%d%H:%M:%S")

def ping(host):
    # 去除IP/域名前后的空白字符,跳过空字符串
    host = host.strip()
    if not host:
        return
    
    results_file = open("results_bng_" + str(timestr) + ".txt", "a")
    try:
        # 执行Ping命令,-n指定发送5次请求
        p = subprocess.Popen(["ping", host, "-n", "5"], shell=True, universal_newlines=True, stdout=subprocess.PIPE)
        response = p.communicate()[0]
        
        latfin1 = "0"
        # 解析延迟数据
        for line in response.split("\n"):
            para = line.split("=")
            try:
                if para[0].strip() == "Minimum":
                    latency = para[3].strip()
                    latfin = re.findall('\d+', latency)
                    if latfin:
                        latfin1 = latfin[0]
            except IndexError:
                # 跳过格式不符合的行
                pass
        
        # 修正UP判断逻辑:5次请求全部收到响应才标记为UP
        if "Received = 5" in response and "Approximate" in response:
            print(f"UP {host} Ping Successful")
            results_file.write(f"{host},UP,{latfin1},{timesec}\n")
        else:
            print(f"Down {host} Ping Unsuccessful")
            results_file.write(f"{host},Down,0,{timesec}\n")
    finally:
        # 确保文件始终关闭,避免资源泄漏
        results_file.close()

# 读取输入文件并解析所有IP/域名
with open(r'ip_file.txt', "r") as server_list_file:
    hosts_list = []
    for line in server_list_file:
        # 按逗号分割每行内容,扩展到总列表中
        items = line.strip().split(',')
        hosts_list.extend(items)

# 多线程批量处理,可根据需求调整线程数
num_threads = 5
current_idx = 0
total_hosts = len(hosts_list)

while current_idx < total_hosts:
    threads = []
    # 启动当前批次的线程
    for i in range(num_threads):
        if current_idx + i >= total_hosts:
            break
        thread = threading.Thread(target=ping, args=(hosts_list[current_idx + i],))
        threads.append(thread)
        thread.start()
    
    # 等待当前批次所有线程执行完成
    for thread in threads:
        thread.join()
    
    current_idx += num_threads

关键修改说明

  • 输入解析适配:逐行读取文件,用逗号分割每行内容,将所有IP/域名合并为扁平列表,同时兼容单条每行和逗号分隔两种格式
  • 无效输入过滤:给每个host添加strip()处理,去除逗号前后的空格,同时跳过空字符串,避免对无效内容执行Ping
  • 线程逻辑优化:原代码线程数固定为1且循环存在漏洞,修改为批量启动多线程,等待当前批次全部完成后再处理下一批,提升执行效率
  • Ping结果判断修正:原代码判断Received = 1不符合-n 5的设定,改为判断Received = 5,确保5次请求全部响应才标记为UP
  • 资源与异常优化:用finally块确保文件一定会关闭,简化无用的异常打印,仅捕获必要的IndexError避免程序崩溃

内容的提问来源于stack exchange,提问作者Ratna Raju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:54:29