0
votes

I am trying to ping a host via a python script, and capture both the output and the exit code of ping. for this I came up with the following python snippet:

ping_command = "ping -c 5 -n -W 4 " + IP
ping_process = os.popen(ping_command)
ping_output = ping_process.read()
exit_code_ping = ping_process.close()
exit_code = os.WEXITSTATUS(exit_code_ping)
print ping_output
print exit_code

and I have observed that if the host with the given IP is down or it's unreachable the code works. However if the host is up it gives me:

exit_code = os.WEXITSTATUS(exit_code_ping)
TypeError: an integer is required

and since I'm pretty beginner in python I have no clue what the problem is here.

Questions: What am I doing wrongly and why is this thing not working ... and most importantly, how can I make it work.

2

2 Answers

2
votes

Btw you can fix your snippet by putting inside try block, when it is success exitcode is None:

try:
    exit_code = os.WEXITSTATUS(exit_code_ping)
    print exit_code
except Exception as er:
    print 'Error: ', er

print ping_output

Better approach is using subprocess :

import subprocess

IP = '8.8.8.100'
ping_command = "ping -c 5 -n -W 4 " + IP

(output, error) = subprocess.Popen(ping_command,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   shell=True).communicate()

print output, error
0
votes