feat(scan): WiFi-ADB 扫描支持自定义/多端口(覆盖 Android 11+ 随机端口)
之前只扫 5555。Android 11+ "无线调试" 用 37000-44999 随机端口, 固定的 adb tcpip 也可改端口。新接口让扫描适配任意端口规格。 新增 parse_port_spec:解析端口规格字符串 - 5555 单端口 - "5555,5556" 逗号分隔 - "37000-37010" 范围(最大 1024 个) - 混合格式与序列输入 - 非法/越界 → 退化为默认 5555 - 单个范围 > 1024 端口直接忽略,避免误扫整个端口段 scan_open_ports 重构: - 接受 ports 参数(list[int]),传 ports 时优先于旧 port=int - 返回 list[(ip, port)] 而不是 list[ip],按 (IP 数值序, port 升序) 稳定排序 discover_adb_devices 支持 ports 参数,按 (ip, port) 逐个 verify_adb_target 接入 GUI 与 webui: - gui_app.py 扫描对话框新增"端口"输入框 + 提示 - gui_app.py 启动重连:上次端口非 5555 时把它一并扫描 - web_gui.py /api/wifi/scan 接受 ports;/api/wifi/auto-reconnect 同上次端口逻辑 新增 13 个 parse_port_spec 单测 + 4 个 scan_open_ports 多端口测试 + 2 个 discover_adb_devices 多端口集成测试。 真机验证:6 端口 (5555 + 37000-37005) × 254 IP,~8.5s 扫完, 正确发现 192.168.5.2:5555 (PEPM00)。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
4ab4504425
commit
52b811d0cb
5 files changed
+317
-35
No files matched your search
@@ -29,6 +29,7 @@ from .wifi_adb_scan import (
|
||||
DiscoveredDevice,
|
||||
discover_adb_devices,
|
||||
get_local_subnet,
|
||||
parse_port_spec,
|
||||
parse_subnet_spec,
|
||||
pick_best_match,
|
||||
)
|
||||
@@ -56,6 +57,7 @@ __all__ = [
|
||||
"DiscoveredDevice",
|
||||
"discover_adb_devices",
|
||||
"get_local_subnet",
|
||||
"parse_port_spec",
|
||||
"parse_subnet_spec",
|
||||
"pick_best_match",
|
||||
"CONFIG_PATH",
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
- get_local_subnet 从本机 WLAN 取出 /24 子网
|
||||
- parse_subnet_spec 解析 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5 等格式
|
||||
- probe_adb_port 并发 TCP 探测一个 IP 的 5555 端口是否打开
|
||||
- parse_port_spec 解析 5555 / 5555,5556 / 37000-40000 端口规格
|
||||
- probe_adb_port 并发 TCP 探测一个 IP 的指定端口是否打开
|
||||
- discover_adb_devices 主入口:扫描子网 + adb connect 验证 + 返回真正能连的设备
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +19,14 @@ from typing import Callable, Iterable, Optional
|
||||
|
||||
DEFAULT_ADB_PORT = 5555
|
||||
|
||||
# 默认扫描端口集合:
|
||||
# - 5555 传统 adb tcpip 端口
|
||||
# - 37000-44999 Android 11+ "无线调试"会用这个范围里的随机端口
|
||||
# (来自 ADB pairing 协议;不是每次都同一个,所以扫描需要范围)
|
||||
# 注意:扫整个 8000 端口区间会慢,所以这里只默认扫 5555。
|
||||
# 用户可在 GUI/CLI 里把 ports 改成 "5555,37000-40000" 等。
|
||||
DEFAULT_ADB_PORTS: tuple[int, ...] = (DEFAULT_ADB_PORT,)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DiscoveredDevice:
|
||||
@@ -168,6 +177,75 @@ def parse_subnet_spec(spec: str) -> list[str]:
|
||||
return out
|
||||
|
||||
|
||||
def parse_port_spec(spec) -> list[int]:
|
||||
"""把端口规格解析成端口列表。支持的格式:
|
||||
|
||||
- 5555 单个整数
|
||||
- "5555" 同上(字符串)
|
||||
- "5555,5556" 逗号分隔
|
||||
- "37000-37010" 范围(含两端)
|
||||
- "5555,37000-37010,40000" 混合
|
||||
- None / 空字符串 → 返回 [DEFAULT_ADB_PORT]
|
||||
- list / tuple → 取整去重保序
|
||||
|
||||
无效项跳过。单个范围超过 1024 个端口会被忽略,避免误扫整个端口区间
|
||||
(扫 65535 个端口 × 254 IP 是不合理的)。
|
||||
"""
|
||||
if spec is None:
|
||||
return [DEFAULT_ADB_PORT]
|
||||
|
||||
if isinstance(spec, (list, tuple)):
|
||||
out: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for item in spec:
|
||||
try:
|
||||
p = int(item)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if 1 <= p <= 65535 and p not in seen:
|
||||
seen.add(p)
|
||||
out.append(p)
|
||||
return out or [DEFAULT_ADB_PORT]
|
||||
|
||||
if isinstance(spec, int):
|
||||
return [spec] if 1 <= spec <= 65535 else [DEFAULT_ADB_PORT]
|
||||
|
||||
if not isinstance(spec, str) or not spec.strip():
|
||||
return [DEFAULT_ADB_PORT]
|
||||
|
||||
out: list[int] = []
|
||||
seen: set[int] = set()
|
||||
|
||||
for part in spec.split(","):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
m = re.match(r"^(\d+)\s*-\s*(\d+)$", part)
|
||||
if m:
|
||||
try:
|
||||
lo, hi = int(m.group(1)), int(m.group(2))
|
||||
except ValueError:
|
||||
continue
|
||||
if not (1 <= lo <= hi <= 65535):
|
||||
continue
|
||||
if (hi - lo + 1) > 1024:
|
||||
continue
|
||||
for p in range(lo, hi + 1):
|
||||
if p not in seen:
|
||||
seen.add(p)
|
||||
out.append(p)
|
||||
continue
|
||||
try:
|
||||
p = int(part)
|
||||
if 1 <= p <= 65535 and p not in seen:
|
||||
seen.add(p)
|
||||
out.append(p)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
return out or [DEFAULT_ADB_PORT]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# TCP 端口探测
|
||||
# ============================================================
|
||||
@@ -196,23 +274,37 @@ def scan_open_ports(
|
||||
timeout: float = 0.3,
|
||||
max_workers: int = 64,
|
||||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||||
) -> list[str]:
|
||||
"""并发扫描一批 IP 的 port,返回开放的 IP 列表。
|
||||
ports: Optional[Iterable[int]] = None,
|
||||
) -> list[tuple[str, int]]:
|
||||
"""并发扫描一批 IP × 端口组合,返回 (ip, port) 列表中开放的项。
|
||||
|
||||
on_progress(done, total) 每完成一个回调一次(用于 GUI 进度条)。
|
||||
Args:
|
||||
ips: IP 列表
|
||||
port: 兼容旧接口的单端口;当 ports 为 None 时使用
|
||||
ports: 要扫描的端口列表;非空时优先于 port
|
||||
timeout: 单次 TCP 探测超时
|
||||
max_workers: 并发数
|
||||
on_progress: on_progress(done, total) 回调
|
||||
|
||||
Returns:
|
||||
list of (ip, port),按 ip 然后 port 升序排序,结果稳定。
|
||||
"""
|
||||
ip_list = list(ips)
|
||||
total = len(ip_list)
|
||||
if total == 0:
|
||||
port_list = list(ports) if ports else [int(port)]
|
||||
if not ip_list or not port_list:
|
||||
return []
|
||||
|
||||
open_ips: list[str] = []
|
||||
targets = [(ip, p) for ip in ip_list for p in port_list]
|
||||
total = len(targets)
|
||||
open_targets: list[tuple[str, int]] = []
|
||||
done = 0
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as ex:
|
||||
future_to_ip = {
|
||||
ex.submit(probe_adb_port, ip, port, timeout): ip for ip in ip_list
|
||||
future_map = {
|
||||
ex.submit(probe_adb_port, ip, p, timeout): (ip, p)
|
||||
for ip, p in targets
|
||||
}
|
||||
for fut in as_completed(future_to_ip):
|
||||
for fut in as_completed(future_map):
|
||||
done += 1
|
||||
if on_progress:
|
||||
try:
|
||||
@@ -221,15 +313,18 @@ def scan_open_ports(
|
||||
pass
|
||||
try:
|
||||
if fut.result():
|
||||
open_ips.append(future_to_ip[fut])
|
||||
open_targets.append(future_map[fut])
|
||||
except Exception:
|
||||
continue
|
||||
# 按 IP 字面排序,扫描结果稳定
|
||||
|
||||
# 按 (ip 数值序, port 升序) 排序,结果稳定
|
||||
try:
|
||||
open_ips.sort(key=lambda s: tuple(int(p) for p in s.split(".")))
|
||||
open_targets.sort(
|
||||
key=lambda t: (tuple(int(p) for p in t[0].split(".")), t[1])
|
||||
)
|
||||
except Exception:
|
||||
open_ips.sort()
|
||||
return open_ips
|
||||
open_targets.sort()
|
||||
return open_targets
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -294,13 +389,15 @@ def discover_adb_devices(
|
||||
probe_timeout: float = 0.3,
|
||||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||||
on_phase: Optional[Callable[[str], None]] = None,
|
||||
ports: Optional[Iterable[int]] = None,
|
||||
) -> list[DiscoveredDevice]:
|
||||
"""扫描局域网,返回所有真的能 adb connect 的设备。
|
||||
|
||||
Args:
|
||||
adb_exe: adb 可执行文件路径
|
||||
subnet_spec: None 表示自动用本机子网;否则按 parse_subnet_spec 解析
|
||||
port: 默认 5555
|
||||
port: 兼容旧接口的单端口;当 ports 为 None 时使用
|
||||
ports: 要扫描的端口列表;可来自 parse_port_spec()
|
||||
probe_timeout: 单个 IP 的 TCP 探测超时(秒)
|
||||
on_progress: on_progress(done, total) 端口扫描进度回调
|
||||
on_phase: on_phase("scanning subnet 192.168.5.0/24") 阶段提示回调
|
||||
@@ -320,35 +417,48 @@ def discover_adb_devices(
|
||||
if not ips:
|
||||
return []
|
||||
|
||||
port_list = list(ports) if ports else [int(port)]
|
||||
if not port_list:
|
||||
port_list = [DEFAULT_ADB_PORT]
|
||||
|
||||
if on_phase:
|
||||
try:
|
||||
on_phase(f"扫描 {subnet_spec}({len(ips)} 个 IP)")
|
||||
ports_label = (
|
||||
f"端口 {port_list[0]}"
|
||||
if len(port_list) == 1
|
||||
else f"{len(port_list)} 个端口"
|
||||
)
|
||||
on_phase(
|
||||
f"扫描 {subnet_spec}({len(ips)} 个 IP × {ports_label})"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2) 端口扫描,过滤掉关 5555 的
|
||||
open_ips = scan_open_ports(
|
||||
# 2) 端口扫描,过滤掉所有指定端口都关闭的 IP
|
||||
open_targets = scan_open_ports(
|
||||
ips,
|
||||
port=port,
|
||||
ports=port_list,
|
||||
timeout=probe_timeout,
|
||||
on_progress=on_progress,
|
||||
)
|
||||
|
||||
if not open_ips:
|
||||
if not open_targets:
|
||||
return []
|
||||
|
||||
if on_phase:
|
||||
try:
|
||||
on_phase(f"发现 {len(open_ips)} 个开放 :{port} 的 IP,验证 ADB")
|
||||
on_phase(
|
||||
f"发现 {len(open_targets)} 个开放端口的 (IP,端口),验证 ADB"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3) 对每个开放 IP 调 adb connect 验证
|
||||
# 3) 对每个开放 (IP,Port) 调 adb connect 验证
|
||||
results: list[DiscoveredDevice] = []
|
||||
for ip in open_ips:
|
||||
target = f"{ip}:{port}"
|
||||
for ip, p in open_targets:
|
||||
target = f"{ip}:{p}"
|
||||
state, message = verify_adb_target(adb_exe, target)
|
||||
dev = DiscoveredDevice(ip=ip, port=port, adb_state=state, message=message)
|
||||
dev = DiscoveredDevice(ip=ip, port=p, adb_state=state, message=message)
|
||||
if state == "connected":
|
||||
dev.model = query_device_model(adb_exe, target)
|
||||
results.append(dev)
|
||||
|
||||
Reference in new issue
Block a user