How to detect what output is and do if statement from it?
-
21-12-2019 - |
質問
Basically I am writing a script in Python that will check for me the status of my servers. I need it to ping five different IPs and then detect what the output is. I will then need an if statement for example:
import.os
Server1 = os.system('ping 123.123.123.123')
if Server1 == 'Request timed out':
print('Server 1 is down.')
else:
print('Server 1 is up.')
I am not exactly sure how to go about this. Let me know.
Thanks.
解決
You posted big X/Y here. You want do do X. You don't know how to do X. You think Y is the best way to do X and are asking about Y. If you want to know about X, see Ivc's comment.
I'm going to answer Y but letting you know that Y is not the best way to do it.
import subprocess
import locale
encoding = locale.getdefaultlocale()[1]
proc = subprocess.Popen(["ping", "123.123.123.123"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
if 'Request timed out' in out.decode(encoding):
print 'the host is down'
else:
print 'the host is up'
Then you would need to decide exactly what to do when the host is down and when the host is up.
所属していません StackOverflow