xiaozai
Posts: 13
Joined: Fri Sep 02, 2016 7:27 am

Combining two ping command using python

Fri Nov 25, 2016 4:21 pm

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

Code: Select all

result = os.system ("ping -c 5 " +hostname)
For copy a packet loss value, i used

Code: Select all

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? Its time consuming if i keep ping the same device two times

User avatar
B.Goode
Posts: 10356
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: Combining two ping command using python

Fri Nov 25, 2016 4:58 pm

(I thought I had seen this query earlier today, but I can't find it in the forums now. Odd?Or impatient?)

Presumably if the target is not accessible you will not get a meaningful value for packet loss?

Or issue the ping once, store the information it returns, and then process that output in multiple ways?

User avatar
davef21370
Posts: 897
Joined: Fri Sep 21, 2012 4:13 pm
Location: Earth But Not Grounded

Re: Combining two ping command using python

Fri Nov 25, 2016 5:39 pm

Code: Select all

import subprocess

url = "www.google.com"

ping = subprocess.Popen(["ping", "-n", "1", url], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print ping.stdout.readlines()
Parse the output and you should get what you need.

Dave.
Apple say... Monkey do !!

User avatar
DougieLawson
Posts: 39301
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Combining two ping command using python

Fri Nov 25, 2016 8:31 pm

Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

Return to “Python”