Python 编写端口扫描工具

发布于 2021-01-25  755 次阅读


0x01 代码

#!/usr/bin/python3

import socket,queue,threading,optparse

q = queue.Queue()

def PorScanner(ip):
    while True:
        port = q.get()
        q.task_done()
        conn = socket.socket()
        try:
            conn.connect((ip,port))
            print(f"[+] {port} is Open")
        except:
            pass
if __name__ == '__main__':
    parser = optparse.OptionParser('python3 port_scan.py -i 127.0.0.1 -p 1-65535 -t 2000')
    parser.add_option('-i','--ip',dest='host',type='string',help='target for scanner')
    parser.add_option('-p','--ports',dest='ports',type='string',default='1-65535',help='ports for scanner  [default=1-65535]')
    parser.add_option('-t','--threading',dest='threadNum',type='int',default=2000,help='threading for scanner  [default=2000]')
    (options,args)=parser.parse_args()
    if options.host and options.ports:
        ip = socket.gethostbyname(options.host)
        if '-' in options.ports:
            startPort=options.ports.split('-')[0]
            endPort=options.ports.split('-')[1]
            for i in range(int(options.threadNum)):
                t = threading.Thread(target=PorScanner,args=(ip,))
                t.setDaemon(True)
                t.start()
            for i in range(int(startPort),int(endPort)):
                q.put(i)
            q.join()
    else:
        parser.print_help()

0x02 运行结果


一切都是兴趣使然