Jack
Jack

Reputation: 5

Combining two ping command in Linux

I have two working command that check a device up/down and copy packet loss value.

For checking a device up and down i used

 result = os.system ("ping -c 5 " +hostname)

For copy a packet loss value, i used

packetloss = os.popen ("ping -c 5 " +hostname+ "| grep -oP '\d+(?=% packet loss)'").read().rstrip()
packetloss = int(packetloss)

I know its not practical to use os.system. My question is how to combine both of the command? For now i need to ping two times just to get device up/down and another ping to check the packet loss value. How can i just ping once to get both result?

Upvotes: 0

Views: 214

Answers (1)

Jaimin Ajmeri
Jaimin Ajmeri

Reputation: 602

Use subprocess. Then you can directly parse the string you need.

Edit: python script is updated.

import subprocess

output = ""
error = ""
hostname = "www.google.com"
try:
    cmd = "ping -c 5 " + hostname
    p = subprocess.Popen([cmd], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    output = str(p[0])
    error = str(p[1])
except Exception, e:
    error = str(e)

if output:
    data = output.split("--- " + hostname + " ping statistics ---")
    print "\nPing output:\n", data[0].strip() 
    statistics = data[-1].strip()
    print "\nStatistics:\n", statistics
    packetloss = str(statistics.splitlines()[0]).split(",")
    packetloss = packetloss[2].strip()
    packetloss = packetloss[:packetloss.find("%")]
    print "\nPacketLoss:", packetloss
if error:
    print "\nError:", error

Upvotes: 1

Related Questions