response = os.system("echo ping -a -c 1 " + hostname1)
The system command you are executing is just an echo
, which will just print "ping -a -c 1 <hostname>
" to stdout, and then return 0. It does not really do any pinging. You can test it by running the system commands directly on a terminal and checking the return value:
$ echo ping -a -c 1 8.8.8.8
ping -a -c 1 8.8.8.8
$ echo $? # returns 0
$ echo ping -a -c 1 <some.invalid.ip>
<some.invalid.ip>
$ echo $? # still returns 0
You should remove echo
and just do:
response = os.system("ping -a -c 1 " + hostname1)
Which should return the correct result:
# VALID IP
>>> response = os.system("ping -a -c 1 8.8.8.8")
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=5.80 ms
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 5.803/5.803/5.803/0.000 ms
>>> print(response)
0
# INVALID IP
>>> response = os.system("ping -a -c 1 5.5.5.5")
PING 5.5.5.5 (5.5.5.5) 56(84) bytes of data.
--- 5.5.5.5 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
>>> print(response)
256
For system calls, I recommend to use the subprocess
package instead, which includes subprocess.run
function that can print the command output and then return an object containing the command's return code.
# VALID IP
>>> response = subprocess.run(["ping", "-c", "1", "8.8.8.8"])
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=5.19 ms
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 5.194/5.194/5.194/0.000 ms
>>> response.returncode
0
# INVALID IP
>>> response = subprocess.run(["ping", "-c", "1", "5.5.5.5"])
PING 5.5.5.5 (5.5.5.5) 56(84) bytes of data.
--- 5.5.5.5 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
>>> response.returncode
1
If you wanted to hide the output of the ping
command, you can pass subprocess.PIPE
to stdout
of subprocess.run
:
>>> response = subprocess.run(["ping", "-c", "1", "5.5.5.5"], stdout=subprocess.PIPE)
>>> response.returncode
1
The recommendation to use subprocess
is noted in the os.system
doc:
The subprocess module provides more powerful facilities for spawning
new processes and retrieving their results; using that module is
preferable to using this function. See the Replacing Older Functions
with the subprocess Module section in the subprocess documentation for
some helpful recipes