Python socket connect_ex()似乎被卡住了,这取决于

2024-04-19 11:36:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的家庭网络上运行端口扫描程序。如果我在家庭网络上的设备上运行它,它只能在其他Linux机器上运行(物理机器而不是vm)。我所说的“works”是指它可以找到实际打开的端口(ssh、mysql、sunrpc和其他几个)。你知道吗

当扫描窗口和其他各种物联网设备时,它只是挂起,永远不会结束。我好像不知道它卡在哪里了。你知道吗

我认为这可能是代码中最相关的部分:

for port in range(begin, end):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        status = s.connect_ex((self.target_ip, port))
    except Exception:
        continue
    finally:
        s.close()
    if status != 0:
        continue
    try:
        service = socket.getservbyport(port)
    except Exception:
        service = "unknown"
    print("SERVICE: %-15s\tPORT: %-8d" % (service, port))

如有任何建议,将不胜感激


Tags: 程序机器portlinuxstatusserviceexception物理
1条回答
网友
1楼 · 发布于 2024-04-19 11:36:08

我修改了您的代码以便可以在我的机器上模拟运行,但它似乎挂起了,因为最后的print语句没有到达。但这是因为if status != 0中的continue行总是返回为“not 0”,至少在我的windows10pro机器上是这样。你知道吗


for port in range(begin, end):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        status = s.connect_ex((self.target_ip, port))
        print("DEBUG: ", status) # add this
    except Exception as err:
        print("Error: ", err) # add this
        continue
    finally:
        s.close()
    if status != 0:
        print("DEBUG: status was not 0") # add this
        # if this line is reached, we start at the top of the loop
        # skipping the try except and print below entirely.
        continue
    try:
        service = socket.getservbyport(port)
    except Exception:
        service = "unknown"
    print("SERVICE: %-15s\tPORT: %-8d" % (service, port))

你能给这个一个镜头,看看是否会发光一些什么可能是错误的或让我们知道你得到什么样的输出。我目前无法在任何Linux机器或物联网设备上运行此功能。我假设您能够读取每个设备上的控制台输出,从而确定它似乎是“挂起”的。你知道吗

编辑1:悬而未决问题的更多上下文

让我给你一些例子,看看这个脚本在我的网络上发生了什么。你知道吗

情况1:'192.168.1.0' 此地址存在,但通常不用于或分配给任何对象。对我来说,每个端口挂起大约20秒。你知道吗

情况2:'192.168.1.1' 这通常是网络上的路由器。立即响应。每个扫描的端口挂起大约1秒。你知道吗

情况3:'192.168.1.3' 此设备在网络范围内,但没有设备正在使用它。每个端口挂起大约20秒(就像案例1一样)。你知道吗

所以长期的“悬念”并不是说它不起作用。它基本上意味着IP错误或者没有达到设备的超时限制,所以套接字连接尝试达到了超时限制,而不是引发异常,它只是继续。你知道吗

编辑2

在遍历大量IP地址和每个被测试IP地址的大量端口之前。有时,通过定义对几个端口和特定IP地址的更多控制,我可以一次测试假设1。你知道吗

这就是我把你的代码转换成的。如果conn不是0,我只是在考虑关闭端口,不管在这种情况下返回了哪个错误代码。我们只关心那些用0响应的,因为这表示操作成功了。你知道吗

import socket

# Lets test just a few custom ports.
ports = [21, 22, 80, 8080]

# And test a specific IP address to test, 1 at a time.
ip = '192.168.1.1' # change this if needed

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

for port in ports:
    # loop through our small custom port range.
    try:
        conn = sock.connect_ex((ip, port))
        if conn == 0:
            print("Port [{}] open.".format(port))
        else:
            print("Port [{}] closed.".format(port))
    except Exception as err:
        print(err)
        continue

    try:
        service = socket.getservbyport(port)
    except Exception:
        service = "unknown"
    print("SERVICE: %-15s\tPORT: %-8d" % (service, port))

sock.close()

我希望这有帮助,让我知道如果你仍然被困。你知道吗

相关问题 更多 >