Python 编写端口扫描工具

发布于 2020-04-01  481 次阅读


0x01 代码

#!/usr/bin/python3

import sys
import socket
import queue
import threading
import time

q = queue.Queue()

class PorScanner(threading.Thread):
    def __init__(self,host):
        super().__init__()
        self.host = host
    def run(self) -> None:
        while True:
            port = q.get()
            self.scanner(port)
            q.task_done()
    def scanner(self,port):
        conn = socket.socket()
        try:
            conn.connect((self.host,port))
            print(f"[+] {port} is Open")
        except:
            pass
def main():
    if len(sys.argv) == 5:
        host = sys.argv[1]
        ip = socket.gethostbyname(host)
        startPort = sys.argv[2]
        endPort = sys.argv[3]
        threadNum = sys.argv[4]
        for i in range(int(threadNum)):
            t = PorScanner(ip)
            t.setDaemon(True)
            t.start()
        for i in range(int(startPort),int(endPort)):
            q.put(i)
        q.join() 
    else:
        print("Tips:python3 port_scan.py <ip> <startPort > <endPort > <thread>")
if __name__ == '__main__':
    try:
        main()
    except:
        pass

0x02 运行结果

0x03 代码

#批量ip.txt扫描端口
#!/usr/bin/python3
import sys
import socket
import threading
import time

def PorScanner(ip,port):
    conn = socket.socket()
    try:
        conn.connect((ip,port))
        print(f"[+]{ip}:{port}is Open")
        conn.close()
    except:
        pass

if __name__ == '__main__':
    if len(sys.argv) == 4:
        txt = sys.argv[1]
        startPort = sys.argv[2]
        endPort = sys.argv[3]
        f = open(txt,'r')
        for i in f:
            ip = i.rstrip('\n')
            for i in range(int(startPort),int(endPort)):
                port = i
                threadl = []
                t = threading.Thread(target=PorScanner,args=(ip,port))
                threadl.append(t)
                for x in threadl:
                    x.start()
                    time.sleep(0.001)
    else:
        print("Tips:python3 port_scan_txt.py <ip.txt> <startPort> <endPort>")

我不懂世界到底在热闹些什么