我如何在每个ping结果中提取平均水平并存储在文件中

发布于 2025-02-09 14:12:13 字数 548 浏览 2 评论 0原文

在这里,我可以ping每个IP,但无法提取结果的平均值。有人可以帮忙吗?

import subprocess
import threading
ip_list = []
def ping(host):
    ip_list.append(host+ ' '+ str((subprocess.run('ping '+host +' -n 1').returncode)))

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

Here I can ping each IP but am not able to extract the Average of the result. Can anyone help, please?

import subprocess
import threading
ip_list = []
def ping(host):
    ip_list.append(host+ ' '+ str((subprocess.run('ping '+host +' -n 1').returncode)))

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对你再特殊 2025-02-16 14:12:13

在进行了一些研究之后,我发现使用subprocess.run,然后获得返回代码,您没有得到输出,但只有返回代码,因此通常0对于成功运行而没有任何错误。
如果要获取流程的输出,则必须使用subprocess.popen,然后进行交流。
然后,如果您只希望平均值,则必须对输出进行一些字符串操作,以在“平均值”之后获得数字。
这是一个景象:

def ping(host):
    output = subprocess.Popen(["ping", host, "-n", "1"], stdout=subprocess.PIPE).communicate()[0]
    words = str(output).split(sep=" ")
    average = words[words.index("Average")+2].split("ms")[0]
    ip_list.append(host+ ' '+ average)

After doing some research I found out that using subprocess.run and then getting the returncode you dont get the output but only the return code so usually 0 for a successfull run with no error.
If you want to get the output of the process you have to use subprocess.Popen and then communicate.
Then if you only want the average you have to do some string manipulation with the output to only get the number after "Average".
Here's an exemple:

def ping(host):
    output = subprocess.Popen(["ping", host, "-n", "1"], stdout=subprocess.PIPE).communicate()[0]
    words = str(output).split(sep=" ")
    average = words[words.index("Average")+2].split("ms")[0]
    ip_list.append(host+ ' '+ average)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文