Python ping脚本

时间:2018-06-13 20:55:27

标签: python bash ping

我正在尝试编写一个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'

1 个答案:

答案 0 :(得分:2)

您应该在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'

此外,您应该考虑使用subprocess module代替os.system(),因为后者已被弃用。