Skip to main content
 首页 » 编程设计

python之使用 Python 实现 ping

2025年05月04日14powertoolsteam

我正在尝试对一系列服务器执行 ping 操作,并且我想存储 ping 操作的输出。据我所知。

import subprocess 
 
string_part = 'ping -W 2 -c 2  64.233.' 
 
for i in range(160,165):             
     for j in range(0,5):    
          prompt = string_part + str(i) + '.' + str(j) 
          result = subprocess.call(prompt, shell = True)     

我想如果我在这之后给出“print(result)”,它会打印出结果。但是,它只返回 1。我现在不想使用线程。我想我错过了什么! :(

请您参考如下方法:

subprocess.call() 返回进程的退出代码。要获取 ping 命令的标准输出输出,请使用 pipe和 Popen.communicate()相反:

string_part = 'ping -W 2 -c 2  64.233.{}.{}' 
 
for i in range(160, 165):             
     for j in range(5):    
          prompt = string_part.format(i, j) 
          proc = subprocess.Popen(prompt, shell=True, stdout=subprocess.PIPE) 
          result, _ = proc.communicate() 

您可以而且应该避免使用 shell;只需传入列表中的参数:

command = ['ping', '-W', '2', '-c', '2']   
ip_template = '64.233.{}.{}' 
 
for i in range(160, 165):             
     for j in range(5):    
          ip_address = ip_template.format(i, j) 
          proc = subprocess.Popen(command + [ip_address], stdout=subprocess.PIPE) 
          result, _ = proc.communicate()