0

我正在为外部 IP 创建一个端口扫描程序,但socket.connect_ex为什么会挂起?不久前我在这里学习了一个教程,然后将其修改为这个。我很困惑为什么它不起作用......

完整代码:

import socket
import subprocess
import random
import sys
# Clear the screen
subprocess.call('cls', shell=True)
for i in range(255):
    remoteServerIP  = "{}.{}.{}.{}".format(random.randint(2, 244), random.randint(2, 244), random.randint(2, 244), random.randint(2, 244))

    # Print a nice banner with information on which host we are about to scan
    print("-" * 60)
    print("Please wait, scanning remote host", remoteServerIP)
    print("-" * 60)

    # Using the range function to specify ports (here it will scans all ports between 1 and 1024)

    # We also put in some error handling for catching errors
    with open("ipAdresses.txt", "a") as f:
        f.write(remoteServerIP)
    try:
        for port in range(1,25567):  
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            result = sock.connect_ex((remoteServerIP, port))
            if result == 0 and port not in range(25, 67, 68) :
                with open("ipAdresses.txt", "a") as f:
                    f.write("    {}\n".format(port))
            sock.close()


    except KeyboardInterrupt:
        print("You pressed Ctrl+C")
        sys.exit()

    except socket.error:
        print("Couldn't connect to server")
        sys.exit()
4

1 回答 1

0

我怀疑这部分是问题所在:

range(25, 67, 68)

这返回

[27]

这(我怀疑)不是理想的行为。相反,我建议您使用:

if result == 0 and port not in (25, 67, 68):

编辑:通过向套接字添加超时来修复代码

这将修复代码:

import socket
import subprocess
import random
import sys
# Clear the screen
subprocess.call('cls', shell=True)
for i in range(255):
    remoteServerIP  = "{}.{}.{}.{}".format(random.randint(2, 244), random.randint(2, 244), random.randint(2, 244), random.randint(2, 244))

    # Print a nice banner with information on which host we are about to scan
    print("-" * 60)
    print("Please wait, scanning remote host", remoteServerIP)
    print("-" * 60)

    # Using the range function to specify ports (here it will scans all ports between 1 and 1024)

    # We also put in some error handling for catching errors
    with open("ipAdresses.txt", "a") as f:
        f.write(remoteServerIP)
    try:
        for port in range(1,25567):  
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex((remoteServerIP, port))
            if result == 0 and port not in (25, 67, 68) :
                with open("ipAdresses.txt", "a") as f:
                    f.write("    {}\n".format(port))
            sock.close()


    except KeyboardInterrupt:
        print("You pressed Ctrl+C")
        sys.exit()

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

注意sock.settimeout(1)线。这会将套接字切换到非阻塞模式(如果未提供,套接字将无限期等待)。

于 2016-12-12T14:47:23.247 回答