#!/usr/bin/env python
#--superzero
#--2014-08-04
import sys
import socket
import threading
import Queue
import time
def scanIt(host,port):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((host,port))
res = host+'\'s ' + str(port)+ ' OPEN!'
except:
#res = ''
res = ' '
#print sys.exc_info()
pass
s.close()
return res
class MyThread(threading.Thread):
def __init__(self, workQueue, resultQueue, timeout=1, *args, **kwargs):
threading.Thread.__init__(self)
self.workQueue = workQueue
self.resultQueue = resultQueue
self.timeout = timeout
self.kwargs = kwargs
self.args = args
self.setDaemon(False)
self.start()
#overwrite run()
def run(self):
while True:
try:
callable, host, port = self.workQueue.get(timeout=self.timeout)
result = callable(host,port)
if result != ' ':
# result = callable(host, port)
self.resultQueue.put(result)
except Queue.Empty:
break
except:
print sys.exc_info()
#raise
pass
class ThreadPool(object):
def __init__(self ,num_of_threads=5):
self.workQueue = Queue.Queue()
self.resultQueue =Queue.Queue()
self.num_of_threads = num_of_threads
self.threads = []
self.createThreadPool(self.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 waitThreadComplet(self):
while len(self.threads):
thread = self.threads.pop()
if thread.isAlive():
thread.join()
def add_job(self, callable, *args):#, **kwargs):
self.workQueue.put((callable, args[0], args[1]))#, kwargs)
#self.resultQueue.put( 'add done')
def main():
w = ThreadPool(5)
print 'start..',time.ctime()
host = '127.0.0.1'
for port in range(1,65535):
w.add_job(scanIt, host, port)
w.waitThreadComplet()
while w.resultQueue.qsize():
print w.resultQueue.get()
print 'end...',time.ctime()
if __name__ == '__main__':
main()
转载于:https://my.oschina.net/superx/blog/299440