Python使用socket多线程扫描端口

# -*- coding: utf8 -*-
import socket
import sys
import threading
import time
import Queue
TIMEOUT = 2
reload(sys)
sys.setdefaultencoding( "utf-8" )
def scan(ip, port, timeout=TIMEOUT):
    try:
        print "Scan " + ip + "  " + str(port)
        cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        cs.settimeout(float(timeout))
        address = (str(ip), int(port))
        status = cs.connect_ex((address))
        if status == 0:
            print "%s ==> %d" % (ip,port)
    except Exception, e:
        print "error:%s" % e
    finally:
        cs.close()
class Scan(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        while True:
            try:
                if queue.empty(): break
                queue_task = self.queue.get()
                ip = queue_task.split(':')[0]
                port = int(queue_task.split(':')[1])
                scan(ip,port)
            except:
                break
def get_ip_list(ip):
    ip_list = []
    iptonum = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])])
    numtoip = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)])
    if '-' in ip:
        ip_range = ip.split('-')
        ip_start = long(iptonum(ip_range[0]))
        ip_end = long(iptonum(ip_range[1]))
        ip_count = ip_end - ip_start
        if ip_count >= 0 and ip_count <= 65536:
            for ip_num in range(ip_start,ip_end+1):
                ip_list.append(numtoip(ip_num))
        else:
            print 'ERROR'
    else:
        ip_split = ip.split('.')
        net = len(ip_split)
        if net == 2:
            for b in range(1, 255):
                for c in range(1, 255):
                    ip = "%s.%s.%d.%d" % (ip_split[0], ip_split[1], b, c)
                    ip_list.append(ip)
        elif net == 3:
            for c in range(1, 255):
                ip = "%s.%s.%s.%d" % (ip_split[0], ip_split[1], ip_split[2], c)
                ip_list.append(ip)
        elif net == 4:
            ip_list.append(ip)
        else:
            print "ERROR"
    return ip_list
if __name__ == '__main__':
    queue = Queue.Queue()
    port = ['80','9200','443','3306']
    ip = '192.168.190.1-192.168.190.50'
    for ipaddress in get_ip_list(ip):
        for p in port:
            queue.put(ipaddress+":"+p)
    threads = []
    num = 10 #设置线程数
    for x in xrange(0, num):
        t_scan = Scan(queue)
        threads.append(t_scan)
    for t in threads:
        t.start()
    for t in threads:
        t.join()