利用Python多线程模块Threading实现端口扫描

  实现步骤:

    1. 打印程序版本信息

    2. 解析输入参数,并对参数进行合法性判断,包括有无正常输入,以及输入的字符串是否为IP地址(利用ipaddress第三方模块)

    3. 实例化PortScanner类,并执行其scan方法,在方法中运用了多线程以及queue模块,用于实现不同线程之间的变量传递

import sys
import socket
import threading
import queue
import optparse
import ipaddress


"""
    Step 1 Banner
    Step 2 Get parameters
    Step 3 Initialize instance of PortScanner Class
    Step 4 Execute function of scan
"""

def banner():
    banner = """
        ******************************************************************
        ******************************************************************
                           PortScanner by Jason Wong V1.0
        ******************************************************************
        ******************************************************************
    """
    print(banner)

def judge_validity_ip(ip):
    try:
        ipaddress.ip_address(ip)
        return True

    except:
        return False

def get_target_info():
    parser = optparse.OptionParser('Usage: <Program> -H <target host>')
    parser.add_option('-H','--host',dest='host', type='string', help='Specify IP address of target')
    options, args = parser.parse_args()
    if options.host is None:
        print(parser.usage)
        sys.exit(0)
    host = options.host
    if not judge_validity_ip(host):
        print("Enter right IP address!")
        sys.exit(0)
    return host

class PortScanner:
    def __init__(self, target):
        self.target = target
        self.q = queue.Queue()
    
    def scanner(self, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        try:
            s.connect((self.target, port))
            res = s.recv(1024).decode('utf-8')
            
            self.q.put((port,res))
        except:
            pass


    
    def scan(self):
        print("Scanned results for the target %s \n" % self.target)
        for port in range(1,65535):
            t = threading.Thread(target=self.scanner, args=(port,))
            t.start()
        while not self.q.empty():
            port, res = self.q.get()
            print("Port is open %d %s" %(port, res))

if __name__ == "__main__":
    banner()
    target_ip = get_target_info()
    portscanner = PortScanner(target_ip)
    portscanner.scan()

 

posted @ 2022-04-20 11:01  Jason_huawen  阅读(168)  评论(0编辑  收藏  举报