为何多次扫描本地IP端口会得到不同结果?
端口扫描结果不稳定的原因及优化方案
问题场景
使用自编Python端口扫描脚本扫描本地IP(命令:python3 myscript.py 127.x.x.x)时,每次扫描结果不一致:第一次无开放端口,第二次扫出2个,第三次仅1个。脚本代码如下:
#!/bin/python # Our goal is to write a script that scans all the ports to an ip and finds the open one! import sys import socket from datetime import datetime size = len(sys.argv) if size !=2: print("You wrote the argument wrong! format : python3 script.py\ Victim's domain or ip") sys.exit() victim = socket.gethostbyname(sys.argv[1]) print("$"*40) print("Searching for open ports on victim: {}".format(victim)) print("Start time: " + str(datetime.now())) print("$"*40) try: for port in range(1,65000): #print("checking {}".format(port)) x=socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) result = x.connect_ex((victim,port)) if result == 0: print("Port {} is open!".format(port)) x.close() except socket.error: print("Could not connect") sys.exit() except socket.gaierror: print("Invalid domain") sys.exit()
结果不稳定的核心原因
- Socket资源耗尽:每次循环都创建新Socket对象,虽然调用了
x.close(),但Linux下TCP连接关闭后会进入TIME_WAIT状态(持续数十秒),短时间内大量创建连接会耗尽本地可用端口,导致后续连接请求失败,漏扫开放端口。 - 超时设置不合理:
socket.setdefaulttimeout(1)是全局设置,重复调用无意义;且本地端口扫描不需要1秒超时——本地连接响应极快,过长超时会拖慢扫描速度,还可能因系统调度问题导致部分连接被误判为超时。 - 本地服务动态变化:如果本地有临时启动的服务(比如调试用的Web服务、临时数据库连接),这些服务在不同扫描时段的启停状态不同,也会导致结果波动。
脚本优化建议
- 单独设置Socket超时:用
x.settimeout(0.1)替代全局设置,只针对当前扫描Socket生效,本地扫描0.1秒超时足够:
x=socket.socket(socket.AF_INET, socket.SOCK_STREAM) x.settimeout(0.1) # 替换全局的socket.setdefaulttimeout
- 优化Socket创建逻辑:避免频繁创建销毁Socket,可在每次连接后重置状态,或适当降低扫描速率(比如添加
time.sleep(0.01)延迟),减少资源消耗。 - 缩小扫描范围:先扫描常用端口(如1-10000)而非全端口,减少连接创建数量,降低端口耗尽概率。
内容的提问来源于stack exchange,提问作者Vindictive
相关产品推荐
相关产品推荐

