python 多线程扫描大批机器端口

代码如下:

#!/usr/bin/env python

import socket
from time import sleep
import Queue
import threading


def put_queue(q):
    with open('D:/vim/alllist','rb') as f:
		for line in f:
			#print 'Put %s to queue' % ([line.split()[2],line.split()[4]]) 
			q.put([line.split()[2],line.split()[4]],block=False)

def get_queue(q,file):
	while True:
		if not q.empty():
			value = q.get(block=False)
			ip = value[0]
			port = value[1]
			#command = "sleep 1 | telnet %s %s" % (value[0],value[1])
			#proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
			#res = proc.stderr.read()
			#if res.endswith('refused\n'):
			#	print "%s %s connected refues" % (value[0],value[1])
			sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			sk.settimeout(5)
			try:
				sk.connect((ip,int(port)))
			except Exception:
                                temp = "Server %s port %s not connect!" % (ip,port)
                                file.write(temp+'\n')
                                file.flush()
			sk.close()
		else:
			break


if __name__ == '__main__':
    f = open('D:/vim/failfile','a+')
    f.truncate()
	q = Queue.Queue()

	t1 = threading.Thread(target=put_queue,args=(q,))
	t1.setDaemon(True)
	t1.start()
	sleep(1)
	num = 10
	threads = []
	for i in xrange(0,num):
		threads.append(threading.Thread(target=get_queue,args=(q,f,)))
	for t in threads:
		t.setDaemon(True)
		t.start()

	for t in threads:
		t.join()
        f.write("done")
        f.close()



你可能感兴趣的:(python,linux)