python 线程池,多线程端口扫描

#!/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值