Ferenc Deak
Ferenc Deak

Reputation: 35408

Python running ping and getting the exit code

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.

Upvotes: 0

Views: 7137

Answers (2)

James Sapam
James Sapam

Reputation: 16940

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

Upvotes: 2

oz123
oz123

Reputation: 28858

Use the subprocess. module, check this excellent piece of documentation about subprocess

Popen.returncode is what you are looking for...

How to get exit code when using Python subprocess communicate method?

Upvotes: 0

Related Questions