Python ping 脚本
Python ping script
我正在尝试编写一个 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'
您应该在 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()
,因为后者已被弃用。
我正在尝试编写一个 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'
您应该在 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()
,因为后者已被弃用。