我的端口扫描程序挂起在connect_ex上?

时间:2016-12-12 08:45:15

标签: python sockets port-scanning

我正在为外部IP创建端口扫描程序,但它挂起same domain为什么?我前一段时间遵循了教程here,并将其修改为此。我为什么不工作而感到困惑......

完整代码:

Esc keyup event

1 个答案:

答案 0 :(得分: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)行。这会将套接字切换到非阻塞模式(如果没有提供,套接字将无限期地等待)。