您的位置:首页 > 编程语言 > Python开发

python 监测主机是否alive

2015-09-22 11:18 459 查看
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys
from threading import Thread
import subprocess
from Queue import Queue

num_threads=3
ips = ['127.0.0.1','192.168.20.140']
q=Queue()

def pingme(i,queue):
while True:
ip = queue.get()
print 'Thread %s pinging %s' %(i,ip)
ret = subprocess.call('ping -c 1 %s' % ip,shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT)
if ret == 0:
print '%s is alive!' % ip
elif ret ==1:
print '%s is down...' % ip
queue.task_done()

for i in range(num_threads):
t = Thread(target=pingme,args=(i,q))
t.setDaemon(True)
t.start()

for ip in ips:
q.put(ip)
print 'main thread waiting..'
q.join();print 'done'

显示:
main thread waiting..
Thread 0 pinging 127.0.0.1
Thread 1 pinging 192.168.20.140
192.168.20.140 is alive!
127.0.0.1 is alive!
done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  主机 python null import