- 用线程安全的队列Queue实现扫描端口数据存储
- 用多线程扫描端口
- 用Thread类实现程序组织
#coding:utf-8 import sys import socket import sys import re from threading import Thread from Queue import Queue class ScanPort(Thread): def __init__(self, target_ip, target_port, q): super(ScanPort, self).__init__() self.target_ip = target_ip self.target_port = target_port self.q = q def scan_port(self): try: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((self.target_ip, self.target_port)) q.put(str(self.target_port) + ‘is opening‘) s.close() except Exception,e: pass def run(self): self.scan_port() if __name__ == ‘__main__‘: port_list = [21, 22, 23, 25, 80, 135, 137, 139, 445, 1433, 1502, 3306, 3389, 8080 ,9015] target_ip = sys.argv[1] q = Queue() portThreadList = [ ScanPort(target_ip, port, q) for port in port_list ] for t in portThreadList: t.setDaemon(True) t.start() for t in portThreadList: t.join() # end进入队列,表示扫描结束 q.put(‘end‘) while True: result = q.get() print result if re.search(r‘end‘, result): break