Search code examples
pythonpython-2.7ping

How can I get the full response after pinging a server and assign it to a variable in Python?


I want to be able to ping a server, and instead of just being returned with 0 or 1, I want to be able to see what you would see if you ran it in terminal your self, for example be able to see how many milliseconds it took for the packet to reach the host and get back.

I am using Python 2.7 and am on Linux, which is why in my code I use -c and not -n. This is the code I am using:

import os
response = os.system("ping -c 1 8.8.8.8)
print response

Solution

  • You should use subprocess.check_output:

    https://docs.python.org/2/library/subprocess.html#subprocess.check_output