如何记录ping的结果?

时间:2019-05-23 20:11:42

标签: python

我有一个运行ping的程序。在我的终端屏幕上,我得到以下信息:

--- google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 47.963/47.963/47.963/0.000 ms
Connection successful

但是在我的控制台上,我只会得到:

Connection successful

我希望控制台显示与终端相同的ping统计信息。我最终将要把ping结果记录到txt或csv文件中,但这将是很困难的。

import platform    # For getting the operating system name
import subprocess  # For executing a shell command
import time
import logging

host = "google.com"

def ping(host):
    param = '-n' if platform.system().lower()=='windows' else '-c'
    command = ['ping', param, '1', host]
    return subprocess.call(command) == 0

while ping(host) == False:
    print("There is no network connection")
    time.sleep(1)
while ping(host) == True:
    print("Connection successful")
    time.sleep(1)

如何获取终端Ping统计信息显示在控制台输出上?

2 个答案:

答案 0 :(得分:1)

要记录命令的完整输出,请使用Popen

import platform    # For getting the operating system name
import subprocess  # For executing a shell command
import time

host = "google.com"

def ping(host):
    param = '-n' if platform.system().lower()=='windows' else '-c'
    command = ['ping', param, '1', host]
    return subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()

while True:
    output = ping(host)
    print(output)
    time.sleep(1)

我在使用Python 3.6.7的Ubuntu上进行了测试

答案 1 :(得分:0)

我为Linux重新编辑了ping 3次并输出到文件。这将有效地告诉您主机是打开还是关闭。它仍然应该打印到终端,您可以使用os.system('pause'),尽管我不记得它是否可以在Linux中使用。

import os

def main():
f=['8.8.8.8','yahoo.com']
    for ips in f:
        response = os.system("ping -c3" + ips)
        if response == 0:
            writeToOut(ips,"host is up")

        else:
            writeToOut(ips, "host is down")


def writeToOut(ip,result):
    f=open('C:/Users/user/Desktop/hostsResults.txt','a')
    ip = ip.rstrip()
    f.write(ip + "," + result + '\n')
    f.close()


main()