:
response = subprocess.Popen(['ping', '-c', '1', host], stdout=subprocess.PIPE).communicate()[0]
if 'bytes from' in response.decode():
return host, True
else:
return host, False
hosts = ['192.168.1.1', '192.168.1.2'] # 添加要ping的主机IP
results = []
for host in hosts:
results.append(ping(host))
for result in results:
if result[1]:
print(result[0], 'is up!')
else:
print(result[0], 'is down.')
如果您要ping的主机数量较多,可以使用multiprocessing库来进行多进程ping操作:
import subprocess
from multiprocessing import Pool
def ping(host):
response = subprocess.Popen(['ping', '-c', '1', host], stdout=subprocess.PIPE).communicate()[0]
if 'bytes from' in response.decode():
return host, True
else:
return host, False
if __name__ == '__main__':
hosts = ['192.168.1.1', '192.168.1.2'] # 添加要ping的主机IP
pool = Pool(processes=4) # 开启4个进程
results = pool.map(ping, hosts)
for result in results:
if result[1]:
print(result[0], 'is up!')
else:
print(result[0], 'is down.')
这段代码会启动4个进程,每个进程会ping一个主机。最后,将所有结果存储在results中,并进行输出。
希望我的答案能够帮助到您。如果您还有其他问题,欢迎随时联系我。