I'm working in Linux/Python 3 and am creating some small scripts which consist of executing some commands inside of Python.
Example: Pinging a server
hostname= "server.com"
response= os.system("ping -c 1 " + hostname)
if response == 0:
print (hostname, 'is up!')
else:
print (hostname, 'is down!')
Output:
PING server.com (10.10.200.55) 56(84) bytes of data.
64 bytes from server.com (10.10.200.55): icmp_seq=1 ttl=61 time=12.4 ms
--- server.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 15.446/15.446/15.446/0.000 ms
server.com is up!
This is working OK but I don ́t need to print everything. How can I get only the first line of the output?
-
Hey are you on linux or windows?Brody Critchlow– Brody Critchlow2022年08月17日 18:02:55 +00:00Commented Aug 17, 2022 at 18:02
-
Hey there. I am in Linuxfr0zt– fr0zt2022年08月18日 08:22:49 +00:00Commented Aug 18, 2022 at 8:22
-
Which version of Python 3 are you using?Daniel Walker– Daniel Walker2022年08月18日 13:40:56 +00:00Commented Aug 18, 2022 at 13:40
2 Answers 2
You can use a subprocess in python3 to discard the output to devnull. Something like this
import subprocess
hostname= "server.com"
response= subprocess.call(["ping", "-c", "1", hostname],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
if response == 0:
print (hostname, 'is up!')
else:
print (hostname, 'is down!')
https://docs.python.org/3/library/subprocess.html#subprocess.DEVNULL
5 Comments
Answer that prints the opening response as well. You may have to tweak the response if you don't want to handle it as a byte string and to handle valid but down hosts.
import subprocess
hostname= "stackoverflow.com"
try:
response= subprocess.check_output(["ping", "-c", "1", hostname])
print (response.split(b'\n')[0])
print (hostname, 'is up!')
except subprocess.CalledProcessError:
print (hostname, 'is down!')