1
votes

I have written the following code and it's working:

#!/usr/bin/python

from os import system
import ipaddress
hostname = ipaddress.ip_address(str(input("Please Enter An IP Address : ")))
response = system("ping -c 1 " + str(hostname))

if response ==0:

        print ("System is UP")
else :
        print ("System is DOWN")

While running the following command, I'm getting following results which are good but I don't need any gibberish output of ping.

Please Enter An IP Address : 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=64 time=0.039 ms

--- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.039/0.039/0.039/0.000 ms System is UP

how can a I redirect following output in some other file or in dev/null:

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=64 time=0.039 ms

--- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.039/0.039/0.039/0.000 ms

and only receive System is UP result as output by running the script.

Please help.

1
You should re-format this question. Your code is all over the placeJoe
system("ping -c 1 " + str(hostname) + "> /dev/null") (by far not the best way, but the quickest)?CristiFati
Instead of os.system, you should use the tools of the subprocess module: docs.python.org/3.6/library/subprocess.html It gives you a lot of control over the output.Sven Festersen
Thanks CristiFati .. It worked.!! Thanks a tonMunazzir Hashmi
Sure Sven Festersen.. I'll try using subprocess module. Thanks :)Munazzir Hashmi

1 Answers

0
votes

You may use subprocess for this. See my example python 3.6 code here:

$ cat main.py 
import subprocess

def main():
    host = input('Host? ')
    proc = subprocess.Popen(['ping', '-c', '1', host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    print(f'stdout: {stdout}\nstderr: {stderr}\nreturn: {proc.returncode}')

if __name__ == '__main__':
    main()

You use subprocess.Popen() to create a process and then execute it using proc.communicate(). This returns a tuple containing the contents of stdin and stderr. In your case you might discard this and only use proc.returncode: If it is 0, ping has finished successfully.

$ python main.py 
Host? 8.8.8.8
stdout: b'PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.\n64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=30.3 ms\n\n--- 8.8.8.8 ping statistics ---\n1 packets transmitted, 1 received, 0% packet loss, time 0ms\nrtt min/avg/max/mdev = 30.355/30.355/30.355/0.000 ms\n'
stderr: None
return: 0

$ python main.py 
Host? localhorst
stdout: b''
stderr: b'ping: localhorst: Der Name oder der Dienst ist nicht bekannt\n'
return: 2