-1

I have the following code which returns the ping status of a devce:

def ping_check(hostname):
    response = os.system("ping -c 3 " + hostname)
    if response == 0:
        pingstatus = "Online"
    else:
        pingstatus = "Offline"
    return pingstatus

That works great and works as intended. However, I want to save the ping output to a variable and I'm not sure how to do that.

The output now looks like this:

>>> hostname = "google.com"
>>> op = os.system("ping -c 3 " + hostname)
PING google.com (172.217.7.206) 56(84) bytes of data.
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=1 ttl=48 time=1.56 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=2 ttl=48 time=1.57 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=3 ttl=48 time=1.52 ms

--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2012ms
rtt min/avg/max/mdev = 1.526/1.552/1.572/0.049 ms
>>> 

I want to save the actual output of the ping to a variable so I can throw it into something to use later on. Any help is greatly appreciated.

Dan
  • 359
  • 5
  • 17
  • 1
    Take a look at `subprocess` module – dcg Sep 05 '19 at 15:12
  • You cannot save the output from `os.system()`, as your program never actually received it - it went directly to your terminal. As dcg said, use `subprocess`. – jasonharper Sep 05 '19 at 15:14

1 Answers1

-1

You can use subprocess.check_output:

import subprocess
output = subprocess.check_output(["ping","-c","3",hostname])

Note that the return value is of type bytes.

Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75