Fix device selection and adb command safety

This commit is contained in:
Codex committed 2026-05-20 18:43:58 +08:00
1 parent 89128deb0f
commit e7a7d3f888
9 files changed
+454 -223

No files matched your search

+183 -78
View File
@@ -1,6 +1,7 @@
import subprocess
from datetime import datetime, timedelta
import os
import sys
import warnings
# PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。
@@ -314,7 +315,6 @@ class underlying_operations:
self._screenshot_log_path = os.path.join(
os.path.dirname(__file__), "logs", "screenshot_calls.jsonl"
)
@staticmethod
def _adb() -> str:
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
@@ -331,6 +331,13 @@ class underlying_operations:
adb = adb[1:-1]
return adb
def _adb_args(self, device_id: str, *args: object) -> list[str]:
return [self._adb_path(), "-s", str(device_id), *[str(arg) for arg in args]]
@staticmethod
def _split_shell_cmd(shell_cmd: str) -> list[str]:
return shlex.split(str(shell_cmd or ""), posix=(os.name != "nt"))
def _ensure_ocr(self):
if self.ocr is not None:
return
@@ -401,15 +408,22 @@ class underlying_operations:
def select_device(self):
"""选择需要连接的设备"""
string = subprocess.Popen(
f"{self._adb()} devices", shell=True, stdout=subprocess.PIPE
result = subprocess.run(
[self._adb_path(), "devices", "-l"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
assert string.stdout is not None
totalstring = string.stdout.read()
totalstring = totalstring.decode("utf-8")
totalstring = result.stdout or ""
# print(totalstring)
pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b"
devicelist = re.findall(pattern, totalstring)
devicelist = []
for line in totalstring.splitlines()[1:]:
parts = line.split()
if len(parts) >= 2 and parts[1] == "device":
devicelist.append(parts[0])
# devicelist = re.compile(r'(\w*)\s*device\b').findall(totalstring)
devicenum = len(devicelist)
if devicenum == 0:
@@ -422,16 +436,21 @@ class underlying_operations:
print("当前存在多台设备连接! 输入数字选择对应设备:")
dictdevice = {}
for i in range(devicenum):
string = subprocess.Popen(
"%s -s %s shell getprop ro.product.device"
% (self._adb(), devicelist[i]),
shell=True,
prop = subprocess.run(
self._adb_args(devicelist[i], "shell", "getprop", "ro.product.device"),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
assert string.stdout is not None
modestring = string.stdout.read().strip() # 去除掉自动生成的回车
modestring = (prop.stdout or "").strip()
print("%s:%s---%s" % (i + 1, devicelist[i], modestring))
dictdevice[i + 1] = devicelist[i]
if not sys.stdin.isatty():
print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。")
return False
num = input()
num = int(num)
while not num in dictdevice.keys():
@@ -1194,26 +1213,38 @@ class underlying_operations:
def click_confirm(self, device_id):
"""点击确认键"""
os.system("%s -s %s shell input keyevent 66" % (self._adb(), device_id))
subprocess.run(
self._adb_args(device_id, "shell", "input", "keyevent", "66"),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
print("点击确认键")
def click_back(self, device_id):
"""点击返回键"""
os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id))
subprocess.run(
self._adb_args(device_id, "shell", "input", "keyevent", "4"),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
print("点击返回键")
# 电量检测方法已删除
def get_device_resolution(self, device_id):
"""获取设备分辨率"""
resolution_info = subprocess.Popen(
"%s -s %s shell wm size" % (self._adb(), device_id),
shell=True,
resolution_info = subprocess.run(
self._adb_args(device_id, "shell", "wm", "size"),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
assert resolution_info.stdout is not None
resolution_info_string = resolution_info.stdout.read()
resolution_info_string = bytes.decode(resolution_info_string)
resolution_info_string = resolution_info.stdout or ""
match = re.search(r"Physical size: (\d+)x(\d+)", resolution_info_string)
if match:
width = int(match.group(1))
@@ -2603,20 +2634,29 @@ class underlying_operations:
执行命令:adb shell input swipe <start_x> <start_y> <end_x> <end_y> <duration_ms>
"""
adb_cmd = self._adb()
# 注意:adb input swipe 的参数顺序是:start_x start_y end_x end_y duration_ms
# 这里 left_up_x/y 是起始位置,right_down_x/y 是结束位置
cmd = f"{adb_cmd} -s {device_id} shell input swipe {left_up_x} {left_up_y} {right_down_x} {right_down_y} {steps}"
cmd = self._adb_args(
device_id,
"shell",
"input",
"swipe",
int(left_up_x),
int(left_up_y),
int(right_down_x),
int(right_down_y),
int(steps),
)
try:
# 使用 subprocess 执行命令,捕获错误输出
result = subprocess.run(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5.0,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
@@ -2651,9 +2691,14 @@ class underlying_operations:
except subprocess.TimeoutExpired:
print("[警告] 滑动操作超时")
except Exception as e:
# 降级到原来的 os.system 方法
# 降级重试一次,保持旧逻辑的宽容行为。
try:
os.system(cmd)
subprocess.run(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except Exception:
print(f"[警告] 滑动操作失败: {type(e).__name__}: {e}")
@@ -2661,15 +2706,16 @@ class underlying_operations:
"""使用 sendevent 方法滑动(需要 root 权限)"""
# 获取触摸设备路径
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p | grep -A 5 ABS_MT",
shell=True,
self._adb_args(device_id, "shell", "getevent", "-p"),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
if "event" not in result.stdout.lower():
if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower():
raise FileNotFoundError("无法找到触摸设备")
# 简化实现:直接使用 input 命令的替代参数
@@ -2685,12 +2731,10 @@ class underlying_operations:
# 使用 uiautomator swipe 命令
# 注意:uiautomator 命令格式可能因 Android 版本而异
# Android 5.0+: uiautomator swipe <x1> <y1> <x2> <y2> [steps]
cmd = (
f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}"
)
result = subprocess.run(
cmd,
shell=True,
self._adb_args(
device_id, "shell", "uiautomator", "swipe", int(x1), int(y1), int(x2), int(y2)
),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5.0,
@@ -2712,11 +2756,12 @@ class underlying_operations:
# 获取触摸设备路径(通常是 /dev/input/eventX)
result = subprocess.run(
f"{self._adb()} -s {device_id} shell getevent -p 2>/dev/null | grep -A 10 ABS_MT",
shell=True,
self._adb_args(device_id, "shell", "getevent", "-p"),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
timeout=3.0,
check=False,
)
@@ -2728,7 +2773,7 @@ class underlying_operations:
# 3. 将屏幕坐标转换为设备坐标
# 4. 发送 DOWN -> MOVE -> UP 事件序列
if "event" not in result.stdout.lower():
if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower():
raise FileNotFoundError("无法找到触摸设备(需要 root 权限)")
# 注意:完整的 sendevent 实现非常复杂,需要:
@@ -2751,7 +2796,12 @@ class underlying_operations:
print(f"[Underlying] click: device_id={device_id} coord=({x},{y})")
except Exception:
pass
os.system("{} -s {} shell input tap {} {}".format(self._adb(), device_id, x, y))
subprocess.run(
self._adb_args(device_id, "shell", "input", "tap", int(x), int(y)),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
def long_press(
self, device_id: str, x: int, y: int, duration_ms: int = 900
@@ -2762,8 +2812,13 @@ class underlying_operations:
d = 300
if d > 2000:
d = 2000
os.system(
f"{self._adb()} -s {device_id} shell input swipe {int(x)} {int(y)} {int(x)} {int(y)} {d}"
subprocess.run(
self._adb_args(
device_id, "shell", "input", "swipe", int(x), int(y), int(x), int(y), d
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
def _run_adb_shell(
@@ -2772,8 +2827,7 @@ class underlying_operations:
"""运行 adb shell 命令,成功返回 True。"""
try:
r = subprocess.run(
f"{self._adb()} -s {device_id} shell {shell_cmd}",
shell=True,
self._adb_args(device_id, "shell", *self._split_shell_cmd(shell_cmd)),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=timeout_seconds,
@@ -2789,8 +2843,7 @@ class underlying_operations:
"""运行 adb shell 命令并捕获输出,返回 (ok, stdout)。"""
try:
r = subprocess.run(
f"{self._adb()} -s {device_id} shell {shell_cmd}",
shell=True,
self._adb_args(device_id, "shell", *self._split_shell_cmd(shell_cmd)),
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
timeout=timeout_seconds,
@@ -2836,10 +2889,6 @@ class underlying_operations:
pass
return ""
@staticmethod # type: ignore[misc]
def _escape_shell_double_quotes(text: str) -> str:
return str(text).replace("\\", "\\\\").replace('"', '\\"')
def set_clipboard_text(self, device_id: str, text: str) -> bool:
"""设置设备剪贴板文本(尽量支持中文)。
@@ -2850,20 +2899,47 @@ class underlying_operations:
if not t:
return False
# 1) cmd clipboard set "..."
esc = self._escape_shell_double_quotes(t)
if self._run_adb_shell(
device_id, f'cmd clipboard set "{esc}"', timeout_seconds=3.0
):
return True
# 1) cmd clipboard set
try:
if (
subprocess.run(
self._adb_args(device_id, "shell", "cmd", "clipboard", "set", t),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
):
return True
except Exception:
pass
# 2) Clipper broadcast: am broadcast -a clipper.set -e text "..."
if self._run_adb_shell(
device_id,
f'am broadcast -a clipper.set -e text "{esc}"',
timeout_seconds=3.0,
):
return True
try:
if (
subprocess.run(
self._adb_args(
device_id,
"shell",
"am",
"broadcast",
"-a",
"clipper.set",
"-e",
"text",
t,
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
):
return True
except Exception:
pass
return False
@@ -2886,11 +2962,19 @@ class underlying_operations:
.replace(">", "\\>")
.replace("|", "\\|")
)
return self._run_adb_shell(
device_id,
f'input text "{self._escape_shell_double_quotes(t)}"',
timeout_seconds=5.0,
)
try:
return (
subprocess.run(
self._adb_args(device_id, "shell", "input", "text", t),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5.0,
check=False,
).returncode
== 0
)
except Exception:
return False
def paste_text(self, device_id: str, text: str) -> bool:
"""优先走剪贴板粘贴,其次兜底 input text。"""
@@ -3005,11 +3089,22 @@ class underlying_operations:
act = str(action or "").strip()
if not act:
return False
esc = self._escape_shell_double_quotes(str(msg or ""))
# 这里不依赖 broadcast 的返回文本,只要命令成功执行就认为 ok
return self._run_adb_shell(
device_id, f'am broadcast -a {act} --es msg "{esc}"', timeout_seconds=3.0
)
try:
return (
subprocess.run(
self._adb_args(
device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", str(msg or "")
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
)
except Exception:
return False
def _adbkeyboard_broadcast_int(
self, device_id: str, action: str, key: str, value: int
@@ -3022,9 +3117,21 @@ class underlying_operations:
v = int(value)
except Exception:
return False
return self._run_adb_shell(
device_id, f"am broadcast -a {act} --ei {k} {v}", timeout_seconds=3.0
)
try:
return (
subprocess.run(
self._adb_args(
device_id, "shell", "am", "broadcast", "-a", act, "--ei", k, v
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
)
except Exception:
return False
def keyevent(self, device_id: str, keycode: int) -> bool:
try:
@@ -3196,16 +3303,14 @@ class underlying_operations:
try:
remote = "/sdcard/window_dump.xml"
subprocess.run(
f"{self._adb()} -s {device_id} shell uiautomator dump {remote}",
shell=True,
self._adb_args(device_id, "shell", "uiautomator", "dump", remote),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,
check=False,
)
subprocess.run(
f'{self._adb()} -s {device_id} pull {remote} "{local_path}"',
shell=True,
[self._adb_path(), "-s", str(device_id), "pull", remote, str(local_path)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,