#!/usr/bin/python
#coding=utf-8
import threading,subprocess
from time import ctime,sleep,time
import queue
queue=queue.Queue()
class ThreadUrl(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue=queue
def run(self):
while True:
host=self.queue.get()
ret=subprocess.call('ping -n 1 -w 1 '+host,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if ret:
print ("%s is down" % host)
else:
print("%s is up" % host)
self.queue.task_done()
def main():
for i in range(10):
t=ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in b:
queue.put(host)
queue.join()
#iplist.txt 测试指定列表中的ip在线情况
a=[]
with open('iplist') as f:
for line in f.readlines():
a.append(line.split()[0])
#测试b列表中的ip在线情况
b=['118.25.'+str(y)+'.'+str(x) for x in range(1,254) for y in range(52,53)] #ping 192.168.3 网段
start=time()
#主函数
main()
print ("Elasped Time:%s" % (time()-start))
1.创建一个队列
queue=queue.Queue()
2.定义一个类继承threading.Thread,传入queue
class ThreadUrl(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue=queue
3.在类中定义run函数,首先从队列中取一个值(IP地址),使用subprocess.call进行ping操作,将返回值赋给ret(通返回值为0,不通则值为1),if语句进行对ret的判断,输出相应的语句,self.queue.task_done()将来判断队列是否结束。
def run(self):
while True:
host=self.queue.get()
ret=subprocess.call('ping -n 1 -w 1 '+host,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if ret:
print ("%s is down" % host)
else:
print("%s is up" % host)
self.queue.task_done()
4.定义我们需要ping的地址,将它们加入到列表中去。
a=[]
with open('iplist') as f:
for line in f.readlines():
a.append(line.split()[0])
5.定义主函数,将所有需要ping的ip地址放入到队列中去, 开启10个线程进行ping操作。
def main():
for i in range(10):
t=ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in b:
queue.put(host)
queue.join()