-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathmobile_proxy.py
More file actions
169 lines (149 loc) · 5.03 KB
/
mobile_proxy.py
File metadata and controls
169 lines (149 loc) · 5.03 KB
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
import subprocess
import sys
from typing import Dict, Any, List
def _run_adb_command(args, timeout: int = 10) -> Dict[str, Any]:
"""
Helper to run an ADB command and return a structured result.
Does NOT depend on the main app so it can be imported standalone.
"""
cmd = ["adb"] + list(args)
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=True,
)
return {
"success": True,
"stdout": result.stdout.strip(),
"stderr": result.stderr.strip(),
"command": " ".join(cmd),
}
except subprocess.CalledProcessError as e:
return {
"success": False,
"stdout": e.stdout.strip() if e.stdout else "",
"stderr": e.stderr.strip() if e.stderr else str(e),
"command": " ".join(cmd),
}
except subprocess.TimeoutExpired:
return {
"success": False,
"stdout": "",
"stderr": f"ADB command timed out: {' '.join(cmd)}",
"command": " ".join(cmd),
}
except Exception as e:
return {
"success": False,
"stdout": "",
"stderr": f"Unexpected error running ADB: {e}",
"command": " ".join(cmd),
}
def get_current_mobile_proxy() -> Dict[str, Any]:
"""
Read the current global http_proxy from the Android device.
"""
result = _run_adb_command(["shell", "settings", "get", "global", "http_proxy"])
value = result["stdout"].strip() if result["success"] else ""
return {
"success": result["success"],
"value": value,
"error": result["stderr"] if not result["success"] else "",
}
def set_mobile_proxy(ip: str, port: str) -> Dict[str, Any]:
"""
Set global http_proxy on the Android device.
Equivalent to:
adb shell settings put global http_proxy 10.10.11.195:8888
"""
proxy_value = f"{ip}:{port}"
result = _run_adb_command(
["shell", "settings", "put", "global", "http_proxy", proxy_value]
)
return {
"success": result["success"],
"proxy": proxy_value,
"error": result["stderr"] if not result["success"] else "",
}
def unset_mobile_proxy() -> Dict[str, Any]:
"""
Clear global http_proxy on the Android device.
Equivalent to:
adb shell settings put global http_proxy :0
"""
result = _run_adb_command(
["shell", "settings", "put", "global", "http_proxy", ":0"]
)
return {
"success": result["success"],
"proxy": ":0",
"error": result["stderr"] if not result["success"] else "",
}
def get_local_proxy_ips() -> Dict[str, Any]:
"""
Get list of local IP addresses that can be used as proxy targets.
Uses `ifconfig` on Unix-like systems and `ipconfig` on Windows.
Returns a dict: { "success": bool, "ips": [ { "ip": str, "label": str }, ... ], "error": str }
"""
is_windows = sys.platform.startswith("win")
cmd = ["ipconfig"] if is_windows else ["ifconfig"]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=5,
check=True,
)
output = result.stdout
except Exception as e:
return {
"success": False,
"ips": [],
"error": f"Failed to run {' '.join(cmd)}: {e}",
}
ips: List[Dict[str, str]] = []
if is_windows:
current_label = None
for line in output.splitlines():
line = line.rstrip()
if not line:
continue
if not line.startswith(" "):
current_label = line.strip()
continue
if "IPv4 Address" in line or "IPv4-adres" in line or "IPv4 Address." in line:
parts = line.split(":")
if len(parts) >= 2:
ip = parts[-1].strip()
if ip and not ip.startswith("127."):
label = current_label or "IPv4"
ips.append({"ip": ip, "label": f"{label} ({ip})"})
else:
current_if = None
for raw_line in output.splitlines():
if not raw_line.strip():
continue
if not raw_line[0].isspace():
current_if = raw_line.split(":", 1)[0].strip()
continue
line = raw_line.strip()
if line.startswith("inet "):
parts = line.split()
if len(parts) >= 2:
ip = parts[1]
if ip and not ip.startswith("127."):
iface = current_if or "iface"
ips.append({"ip": ip, "label": f"{iface} ({ip})"})
seen = set()
unique_ips: List[Dict[str, str]] = []
for item in ips:
ip = item["ip"]
if ip in seen:
continue
seen.add(ip)
unique_ips.append(item)
return {"success": True, "ips": unique_ips, "error": ""}