星期一, 10月 30, 2023

Python 土炮 port scanner

 本座想在 VPS 上架服務,但是又怕防火牆擋著連不到,就從 Stack overflow上的答案改了個土炮 port scanner,可應用於快速檢測哪些 outbound port 有開。本座主要修改為設定 thread 的數目上限避免執行環境出錯無法 create thread。小工具速度一般,但也夠用了,而且乾淨、方便。 

# This script runs on Python 3
import socket, threading


def TCP_connect(ip, port_number, delay, output):
    TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    TCPsock.settimeout(delay)
    try:
        TCPsock.connect((ip, port_number))
        output[port_number] = 'Listening'
    except:
        output[port_number] = ''



def scan_ports(host_ip, delay):

    threads = []        # To run TCP_connect concurrently
    output = {}         # For printing purposes

    num_thread = 64
    
    for port_range in range(0,10000,num_thread):
        # Spawning threads to scan ports
        threads = []
        for i in range(num_thread):
            t = threading.Thread(target=TCP_connect, args=(host_ip, port_range+i, delay, output))
            threads.append(t)

        # Starting threads
        for i in range(num_thread):
            threads[i].start()

        # Locking the main thread until all threads complete
        for i in range(num_thread):
            threads[i].join()

        # Printing listening ports from small to large
        for i in range(num_thread):
            if output[port_range+i] == 'Listening':
                print(str(port_range+i) + ': ' + output[port_range+i])



def main():
    host_ip = input("Enter host IP: ")
    delay = int(input("How many seconds the socket is going to wait until timeout: "))   
    scan_ports(host_ip, delay)

if __name__ == "__main__":
    main()
全文連結

0 意見: