0

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 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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?

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.