在python中从ping结果中提取丢包数据

时间:2018-02-23 10:56:56

标签: python-3.x subprocess ping

我正在尝试从ping统计信息中获取 packetloss 数据。到目前为止,我有一大堆ping统计数据。我只需要数据包丢失数据,以便在我的python代码中执行if packetloss < 10%: do something。这是我的代码:

import subprocess
from subprocess import Popen, PIPE

hostname = "8.8.8.8"
process = subprocess.Popen(['ping','-c','5',hostname],
stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)

1 个答案:

答案 0 :(得分:0)

示例数据:

$ ping -c 5 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=59 time=7.250 ms
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2
64 bytes from 8.8.8.8: icmp_seq=3 ttl=59 time=19.661 ms

--- 8.8.8.8 ping statistics ---
5 packets transmitted, 2 packets received, 60.0% packet loss
round-trip min/avg/max/stddev = 7.250/13.456/19.661/6.205 ms

请尝试以下操作:

packetloss = float([x for x in stdout.decode('utf-8').split('\n') if x.find('packet loss') != -1][0].split('%')[0].split(' ')[-1])
if loss < 10.0:
    print("Loss is %s percent" % packetloss)