Austin
Austin

Reputation: 55

Extracting packet loss data from ping result in python

I am trying to get packetloss data from ping statistics. So far, I have a whole chunk of ping statistics data. I only need packetloss data in order to do if packetloss < 10%: do something in my python code. Here's my code:

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)

Upvotes: 1

Views: 4907

Answers (1)

shantanoo
shantanoo

Reputation: 3704

Sample Data:

$ 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

Try following:

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)

Upvotes: 2

Related Questions