- 论坛徽章:
- 0
|
使用线程池写了一个:
scan.py
#!/usr/bin/env python
# coding=utf-8
import os
import sys
import Queue
import socket
import threading
import time
from ThreadPool import ThreadPool
def scan(ip):
s = socket.socket()
s.settimeout(1)
try:
s.connect((ip,22))
print "\n IP : %s , SSH is Opened" %ip
except:
print " \n IP : %s , SSH is Closed" %ip
if __name__ == "__main__":
print "Start Scaning ..."
tp = ThreadPool(10)
for i in xrange(0,254):
tp.add_job( scan, "192.168.10.%s" %str(i+1))
tp.wait_for_complete()
print "Scaning Complete !"
ThreadPool.py
#!/usr/bin/env python
#coding:utf-8
#email:biansutao 【at】 gmail 【dot】com
import Queue
import threading
import sys
import time
import urllib
#替我们工作的线程池中的线程
class MyThread(threading.Thread):
def __init__(self, workQueue, resultQueue,timeout=3, **kwargs):
threading.Thread.__init__(self, kwargs=kwargs)
#线程在结束前等待任务队列多长时间
self.timeout = timeout
self.setDaemon(True)
self.workQueue = workQueue
self.resultQueue = resultQueue
self.start()
def run(self):
while True:
try:
#从工作队列中获取一个任务
callable, args = self.workQueue.get(timeout=self.timeout)
#我们要执行的任务
callable(args)
except Queue.Empty: #任务队列空的时候结束此线程
break
except :
print sys.exc_info()
raise
class ThreadPool:
def __init__( self, num_of_threads=10):
self.workQueue = Queue.Queue()
self.resultQueue = Queue.Queue()
self.threads = []
self.__createThreadPool( num_of_threads )
def __createThreadPool( self, num_of_threads ):
for i in range( num_of_threads ):
thread = MyThread( self.workQueue, self.resultQueue )
self.threads.append(thread)
def wait_for_complete(self):
#等待所有线程完成。
while len(self.threads):
thread = self.threads.pop()
#等待线程结束
if thread.isAlive():#判断线程是否还存活来决定是否调用join
thread.join()
def add_job( self, callable, *args):
self.workQueue.put( (callable,args) )
[ 本帖最后由 biansutao 于 2009-4-30 16:35 编辑 ] |
|