2

I am trying to write a Python script that pings IP addresses and outputs whether each ping succeeded. So far I have the following code, but the output seems inaccurate. Namely, when I run the script, it pings each hostname as expected but the output is only ever all up or all down.

import os

hostname0 = "10.40.161.2"
hostname1 = "10.40.161.3"
hostname2 = "10.40.161.4"
hostname3 = "10.40.161.5"

response = os.system("ping -c 1 " + hostname0)
response = os.system("ping -c 1 " + hostname1)
response = os.system("ping -c 1 " + hostname2)
response = os.system("ping -c 1 " + hostname3)

if response == 0:
    print hostname0, 'is up'
    print hostname1, 'is up'
    print hostname2, 'is up'
    print hostname3, 'is up'
else:
    print hostname0, 'is down'
    print hostname1, 'is down'
    print hostname2, 'is down'
    print hostname3, 'is down'
3
  • 2
    you are continually resetting response. By the if statement, it is only based on the response to hostname8. Commented Jun 13, 2018 at 20:58
  • 1
    Consider looping through a list and printing the response. Commented Jun 13, 2018 at 20:59
  • 1
    As a side note: that the docs for os.system explicitly tell you that "The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function." Commented Jun 13, 2018 at 21:08

1 Answer 1

10

You should print the result immediately after pinging each hostname. Try this:

import os

hostnames = [
    '10.40.161.2',
    '10.40.161.3',
    '10.40.161.4',
    '10.40.161.5',
]

for hostname in hostnames:
    response = os.system('ping -c 1 ' + hostname)
    if response == 0:
        print(hostname, 'is up')
    else:
        print(hostname, 'is down')

Also, you should consider using the subprocess module instead of os.system() as the latter is deprecated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.