1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
|
import argparse
import sys
import time
import uiautomator2 as u2
WLAN_TEXTS = ["WLAN", "Wi‑Fi", "WiFi", "WLAN 和互联网", "网络和互联网"]
PROXY_TEXTS = ["代理", "Proxy"]
MANUAL_TEXTS = ["手动", "Manual"]
SAVE_TEXTS = ["保存", "Save", "应用", "Apply"]
BACK_IDS = [
"com.oplus.wirelesssettings:id/coui_toolbar_back_view",
"com.android.settings:id/action_bar", # 某些机型返回按钮容器
]
LAUNCHER_PKGS = [
"com.android.launcher3",
"com.google.android.apps.nexuslauncher",
"com.coloros.launcher",
"com.oneplus.launcher",
"com.miui.home",
"com.huawei.android.launcher",
"org.lineageos.launcher",
]
def log(msg):
print(f"[INFO] {msg}")
def err(msg):
print(f"[ERROR] {msg}", file=sys.stderr)
def sh(d, cmd):
r = d.shell(cmd)
# 统一拿到纯文本
if isinstance(r, dict) and "output" in r:
out = r["output"]
elif hasattr(r, "output"):
out = r.output
else:
out = r
if out is None:
return ""
if isinstance(out, (bytes, bytearray)):
out = out.decode("utf-8", errors="ignore")
return str(out)
def is_wifi_on(d):
# 优先从 dumpsys 读状态
txt = sh(d, 'dumpsys wifi | grep -iE "wi-?fi is" || true').lower()
if "enabled" in txt:
return True
if "disabled" in txt:
return False
# 退化到全局设置(有些系统可能返回 "null")
val = sh(d, "settings get global wifi_on || true").strip()
return val == "1"
def ensure_wifi_on(d, timeout=10):
sh(d, "svc wifi enable || true")
end = time.time() + timeout
while time.time() < end:
if is_wifi_on(d):
return True
time.sleep(0.4)
return False
def wait_and_click_text(d, candidates, timeout=10, must=True):
end = time.time() + timeout
while time.time() < end:
for t in candidates if isinstance(candidates, list) else [candidates]:
obj = d(text=t)
if obj.exists:
obj.click()
return True
time.sleep(0.3)
if must:
raise RuntimeError(f"找不到文本: {candidates}")
return False
def wait_exists_text(d, candidates, timeout=10):
end = time.time() + timeout
while time.time() < end:
for t in candidates if isinstance(candidates, list) else [candidates]:
if d(text=t).exists:
return t
time.sleep(0.3)
return None
def scroll_to_text_and_click(d, target_text, max_swipes=10):
for _ in range(max_swipes):
if d(text=target_text).exists:
d(text=target_text).click()
return True
if d(scrollable=True).exists:
d(scrollable=True).scroll.vert.forward(steps=30)
else:
d.swipe_ext("up", 0.8)
time.sleep(0.2)
raise RuntimeError(f"滚动仍未找到: {target_text}")
def go_home(d, timeout=0):
d.press("home")
if timeout <= 0:
# 直接返回,不等待检测
return True
end = time.time() + timeout
while time.time() < end:
cur = d.app_current() or {}
if cur.get("package") in LAUNCHER_PKGS:
return True
time.sleep(0.1)
d.press("home")
# 兜底,不阻塞
d.shell("am start -a android.intent.action.MAIN -c android.intent.category.HOME")
return True
def click_any_back(d, isGoHome=False, go_home_timeout=0):
for t in SAVE_TEXTS:
if d(text=t).exists:
d(text=t).click()
break
else:
for rid in BACK_IDS:
if d(resourceId=rid).exists:
d(resourceId=rid).click()
break
else:
d.press("back")
if isGoHome:
go_home(d, timeout=go_home_timeout)
def set_edit_texts(d, host, port, clear_first=True):
# 代理为“手动”后,通常会出现两个 EditText:主机、端口
# 避免复杂 XPath,直接找可见的 EditText
edits = d(className="android.widget.EditText")
if len(edits) < 2:
# 可能未滚到位或控件延迟出现,再尝试滚动几次
for _ in range(4):
d.swipe_ext("up", 0.7)
time.sleep(0.2)
edits = d(className="android.widget.EditText")
if len(edits) >= 2:
break
if len(edits) < 2:
raise RuntimeError("未找到代理主机/端口输入框")
host_edit = edits[0]
port_edit = edits[1]
if clear_first:
try:
host_edit.clear_text()
port_edit.clear_text()
except Exception:
pass
host_edit.set_text(host)
port_edit.set_text(str(port))
def restart_settings(d):
# 部分厂商把 Wi‑Fi 界面放在自家包里,一起停更稳
for pkg in ("com.android.settings", "com.oplus.wirelesssettings"):
d.app_stop(pkg)
d.shell(f"am force-stop {pkg} || true")
# d.press("home")
d.app_start("com.android.settings")
d.app_wait("com.android.settings", timeout=10)
def open_wifi_settings(d):
ensure_wifi_on(d) # 先通过 shell 打开 Wi‑Fi
log("打开设置并进入 WLAN/Wi‑Fi")
restart_settings(d)
# 有些机型首页不直接显示 WLAN,需要滚动或进“网络和互联网”
found = wait_exists_text(d, WLAN_TEXTS, timeout=3)
if not found:
# 可能是“网络和互联网”一级菜单
wait_and_click_text(d, ["网络和互联网", "Network & internet"], timeout=8, must=False)
# 进入后再找 WLAN
wait_and_click_text(d, WLAN_TEXTS, timeout=8, must=True)
else:
wait_and_click_text(d, WLAN_TEXTS, timeout=3, must=True)
def set_wifi_proxy(d, ssid, host, port, wait=10):
log(f"进入 Wi‑Fi: {ssid}")
# 滚动找到对应 SSID
scroll_to_text_and_click(d, ssid, max_swipes=12)
time.sleep(0.3)
# 展开“代理”选项并选择“手动”
log("设置代理为手动")
# 页面可能有“高级选项”,先展开
if d(text="高级选项").exists:
d(text="高级选项").click()
# 滚动确保能看到“代理”
for _ in range(4):
if d(text=PROXY_TEXTS[0]).exists or d(text=PROXY_TEXTS[1]).exists:
break
d.swipe_ext("up", 0.7)
time.sleep(0.2)
wait_and_click_text(d, PROXY_TEXTS, timeout=wait, must=True)
wait_and_click_text(d, MANUAL_TEXTS, timeout=wait, must=True)
# 设置主机和端口
log(f"填入代理 {host}:{port}")
set_edit_texts(d, host, port)
# 保存/返回
click_any_back(d, isGoHome=True,go_home_timeout=0)
def main():
parser = argparse.ArgumentParser(description="通过 uiautomator2 设置指定 Wi‑Fi 的 HTTP 代理")
parser.add_argument("--device", help="设备IP(可选,默认USB或已配对)", default=None)
parser.add_argument("--ssid", required=True, help="Wi‑Fi SSID")
parser.add_argument("--host", required=True, help="代理主机")
parser.add_argument("--port", required=True, type=int, help="代理端口")
parser.add_argument("--wait", type=int, default=10, help="等待超时秒数")
args = parser.parse_args()
try:
#连接设备
d = u2.connect(args.device) if args.device else u2.connect()
#可以传入连接的超时时间
d.implicitly_wait(args.wait)
try:
#打开设置页
open_wifi_settings(d)
time.sleep(1)
set_wifi_proxy(d, args.ssid, args.host, args.port, wait=args.wait)
log("完成")
except Exception as e:
err(str(e))
sys.exit(1)
except Exception as e:
err("未连接到设备,请检查 USB 或 IP 是否正确")
sys.exit(1)
if __name__ == "__main__":
main()
|