bash Python ping 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50846131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python ping script
提问by Melissa Chillington
I am trying to write a Python script that pings IP addresses and outputs whether each ping succeeded. So far I have the following code, but the output seems inaccurate. Namely, when I run the script, it pings each hostname as expected but the output is only ever all up or all down.
我正在尝试编写一个 Python 脚本来 ping IP 地址并输出每个 ping 是否成功。到目前为止,我有以下代码,但输出似乎不准确。也就是说,当我运行脚本时,它会按预期 ping 每个主机名,但输出只会全部启动或全部关闭。
import os
hostname0 = "10.40.161.2"
hostname1 = "10.40.161.3"
hostname2 = "10.40.161.4"
hostname3 = "10.40.161.5"
response = os.system("ping -c 1 " + hostname0)
response = os.system("ping -c 1 " + hostname1)
response = os.system("ping -c 1 " + hostname2)
response = os.system("ping -c 1 " + hostname3)
if response == 0:
print hostname0, 'is up'
print hostname1, 'is up'
print hostname2, 'is up'
print hostname3, 'is up'
else:
print hostname0, 'is down'
print hostname1, 'is down'
print hostname2, 'is down'
print hostname3, 'is down'
回答by ndmeiri
You should print the result immediately after pinging each hostname. Try this:
您应该在 ping 每个主机名后立即打印结果。尝试这个:
import os
hostnames = [
'10.40.161.2',
'10.40.161.3',
'10.40.161.4',
'10.40.161.5',
]
for hostname in hostnames:
response = os.system('ping -c 1 ' + hostname)
if response == 0:
print hostname, 'is up'
else:
print hostname, 'is down'
Also, you should consider using the subprocess
moduleinstead of os.system()
as the latter is deprecated.
此外,您应该考虑使用该subprocess
模块而不是os.system()
后者已被弃用。