如何循环端口扫描?

How do I loop ports to scan?

我的 portscanner 有这个问题,它一直挂在扫描端口 1。我该如何解决这个问题?

    #! /usr/bin/env python

    import socket 
    import subprocess
    from datetime import datetime

    #Clear the screen
    subprocess.call('clear', shell=True)

    def portscan():
        server = raw_input("Enter the server to scan: ")
        serverIP = socket.gethostbyname(server)

        # Printing banner with information about host
        print "[+] Host: {} [+]\nIP Address: {}\n".format(server, serverIP)
        print "[!] Please wait, scanning for open services...\n"

        #Time when scan started.
        t1 = datetime.now()

        try:
            for port in range(1, 1024):
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                result = sock.connect_ex((serverIP, port))
                if result == 0:
                    print "[+] Port {}: Status:OPEN\n".format(result)
                    sock.close()

        except socket.gaierror:
            print "Hostname could not be resolved, Exiting...\n"
            sys.exit()

        except socket.error:
           print "Couldn\'t connect to server, Exiting\n"
           sys.exit()

        #Checking time again
        t2 = datetime.now()
        #Calculate duration of scan
        totaltime = t2 - t1

        print "Scan completed, duration: {}\n".format(totaltime)  

What happens when i run it i give it a hostname and resolve it to a IP Address but whenever the scan starts it keeps scanning port 1 as i saw in Wireshark

我认为您可能需要 timeout

最终,您的 sock.connect_ex( ) 将引发异常 socket.error: [Errno 110] Connection timed out,您可以在 answer.

中阅读更多相关信息

但是默认超时可能是 120 秒,也许您不想等那么久。所以,你可以像这样设置自己的超时时间:

try:
    for port in range(1, 1024):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(10) #timeout set for wait up 10 seconds.
        result = sock.connect_ex((serverIP, port))
        sock.settimeout(None)

要了解为什么要使用 sock.settimeout(None),并查看另一种设置 timeout 的方法,您可以阅读此 discussion

我不确定这是否是您要查找的内容,但我希望它能对您有所帮助。