python 多线程 ping

python 多线程 ping

多线程操作可按如下例子实现

#!/usr/bin/env python
#encoding: utf8

import subprocess
from threading import Thread   
from Queue import Queue  

def ping(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=subprocess.PIPE)  
        if ret==0:  
            print '%s is alive!' %ip  
        elif ret==1:  
            print '%s is down...'%ip  
        queue.task_done()  
  
q=Queue()
ips=['127.0.0.1','116.56.148.187','47.97.184.87']
#command = "awk '{print $1}' iplist"
#p = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE)
#ips = p.stdout.read().split('\n')
#while '' in ips:
#    ips.remove('')
    
for i in range(5):  
    t=Thread(target=ping,args=(i,q))  
    t.setDaemon(True)  
    t.start()  

for ip in ips:  
    q.put(ip)  
q.join()

转载于:https://www.cnblogs.com/Mrhuangrui/p/9260075.html

你可能感兴趣的:(python 多线程 ping)