python 監測主機是否alive

#!/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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章