A-A+
linux多线程执行命令(扫描存活主机)
#!/usr/bin/env python from threading import Thread import subprocess from Queue import Queue import time num_threads=10 iprange='192.168.230.' ips=[] iplist=range(250) for i in iplist: ips.append(iprange+str(i)) #print ips #time.sleep(5) #ips=['127.0.0.1','116.56.148.187','192.168.230.1','192.168.230.2','192.168.230.4'] q=Queue() def pingme(i,queue): while True: ip=queue.get() # print 'Thread %s pinging %s' %(i,ip) ret=subprocess.call('ping -w 2 -c 1 %s' % ip,shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) if ret==0: print '\033[1;32;1m %s is alive! \033[0m' %ip elif ret==1: print '%s is down...'%ip queue.task_done() #start num_threads threads 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'