Skip to content

Commit a20ebf5

Browse files
committed
refactor(agent,teacher): extract shared utils to common/utils; remove wincli_escape
1 parent 0b381cf commit a20ebf5

14 files changed

Lines changed: 150 additions & 203 deletions

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ __pycache__/
1515
# Clash Meta
1616
mihomo.exe
1717
configs/config.yaml
18+
agent/configs
1819

1920
# Trae
2021
.trae/

agent/configs/GeoIP.dat

-18.7 MB
Binary file not shown.

agent/configs/cache.db

-32 KB
Binary file not shown.

agent/firewall_manager.py

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
from __future__ import annotations
44

55
import os
6+
import sys
7+
import time
68
import shutil
79
import socket
8-
import subprocess
9-
import sys
10-
import tempfile
1110
import threading
12-
import time
11+
import subprocess
1312
from typing import Any, Dict, List, Optional, Tuple
13+
from common.utils import is_admin, get_subprocess_flags
1414

1515
_script_dir = os.path.dirname(os.path.abspath(sys.executable)) if getattr(sys, "frozen", False) else os.path.dirname(os.path.abspath(__file__))
1616
CLASH_CONFIG_DIR = os.path.join(_script_dir, "configs")
@@ -20,20 +20,6 @@
2020
_clash_process: Optional[subprocess.Popen] = None
2121

2222

23-
def _subprocess_flags() -> int:
24-
return subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
25-
26-
27-
def is_admin() -> bool:
28-
if sys.platform != "win32":
29-
return False
30-
try:
31-
import ctypes
32-
return bool(ctypes.windll.shell32.IsUserAnAdmin())
33-
except Exception:
34-
return False
35-
36-
3723
def _get_clash_binary_path() -> Tuple[bool, str]:
3824
script_dir = os.path.dirname(os.path.abspath(__file__))
3925
project_root = os.path.dirname(script_dir)
@@ -239,7 +225,7 @@ def _start_clash_process(clash_path: str) -> Tuple[bool, str]:
239225
[clash_path, "-f", CLASH_CONFIG_FILE, "-d", CLASH_CONFIG_DIR],
240226
stdout=subprocess.DEVNULL,
241227
stderr=subprocess.DEVNULL,
242-
creationflags=_subprocess_flags(),
228+
creationflags=get_subprocess_flags(),
243229
)
244230
time.sleep(1.5)
245231
if _clash_process.poll() is not None:
@@ -376,4 +362,4 @@ def get_current_restriction_status() -> Dict[str, Any]:
376362
except Exception:
377363
pass
378364

379-
return status
365+
return status

agent/machine_identity.py

Lines changed: 8 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,15 @@
22

33
from __future__ import annotations
44

5-
import json
65
import re
7-
import subprocess
86
import sys
9-
from typing import Dict, List, Tuple
10-
7+
import json
8+
import subprocess
9+
from typing import List, Tuple
10+
from common.utils import get_subprocess_flags, parse_wmic_list
1111
from agent.network_config import get_default_ipv4_interface_name
1212

1313

14-
def _subprocess_flags() -> int:
15-
return subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
16-
17-
18-
def _parse_wmic_list(text: str) -> List[Dict[str, str]]:
19-
text = text.replace("\r\r\n", "\n").replace("\r\n", "\n").replace("\r", "\n").strip()
20-
blocks = re.split(r"\n\s*\n", text)
21-
rows: List[Dict[str, str]] = []
22-
for block in blocks:
23-
item: Dict[str, str] = {}
24-
for line in block.splitlines():
25-
line = line.strip()
26-
if not line or "=" not in line:
27-
continue
28-
k, v = line.split("=", 1)
29-
item[k.strip().lower()] = v.strip()
30-
if item:
31-
rows.append(item)
32-
return rows
33-
34-
3514
def _normalize_mac(mac: str) -> str:
3615
if not mac:
3716
return ""
@@ -92,12 +71,12 @@ def _physical_adapter_mac_rows_wmi() -> List[Tuple[str, str]]:
9271
capture_output=True,
9372
text=True,
9473
timeout=30,
95-
creationflags=_subprocess_flags(),
74+
creationflags=get_subprocess_flags(),
9675
)
9776
if p.returncode != 0:
9877
return []
9978
out: List[Tuple[str, str]] = []
100-
for row in _parse_wmic_list(p.stdout or ""):
79+
for row in parse_wmic_list(p.stdout or ""):
10180
ne = row.get("netenabled", "").strip().lower()
10281
if ne in ("false", "0"):
10382
continue
@@ -139,7 +118,7 @@ def _physical_adapter_mac_rows_powershell() -> List[Tuple[str, str]]:
139118
capture_output=True,
140119
text=True,
141120
timeout=45,
142-
creationflags=_subprocess_flags(),
121+
creationflags=get_subprocess_flags(),
143122
)
144123
except (OSError, subprocess.TimeoutExpired):
145124
return []
@@ -188,4 +167,4 @@ def get_machine_id() -> str:
188167
return "nonwin"
189168

190169
mac = _get_preferred_mac_normalized()
191-
return mac or "mac-unknown"
170+
return mac or "mac-unknown"

agent/main.py

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,22 @@
22

33
from __future__ import annotations
44

5-
import argparse
6-
import json
75
import os
8-
import platform
6+
import sys
7+
import json
8+
import time
99
import random
1010
import socket
11-
import subprocess
12-
import sys
11+
import argparse
12+
import platform
1313
import threading
14-
import time
15-
from typing import Any, Dict, Optional
16-
14+
import subprocess
1715
from PIL import Image, ImageDraw
18-
16+
from common.utils import is_admin
17+
from typing import Any, Dict, Optional
18+
from agent.rename_host import rename_computer
1919
from common.paths import default_agent_config_path, resolve_config_path
20+
from agent.machine_identity import get_machine_id, get_preferred_mac_display
2021
from common.protocol import (
2122
MSG_ACK,
2223
MSG_COMMAND_NETWORK_RESTRICT,
@@ -35,16 +36,12 @@
3536
read_frame_from_socket,
3637
write_frame_to_socket,
3738
)
38-
39-
from agent.machine_identity import get_machine_id, get_preferred_mac_display
4039
from agent.network_config import (
4140
apply_ipv4_dhcp,
4241
apply_ipv4_static,
4342
get_default_ipv4_detail_snapshot,
4443
get_default_ipv4_interface_name,
45-
is_admin,
4644
)
47-
from agent.rename_host import rename_computer
4845
from agent.firewall_manager import (
4946
apply_blacklist,
5047
apply_whitelist,
@@ -209,8 +206,6 @@ def _register(self, conn: socket.socket) -> bool:
209206
"ipv4_detail": get_default_ipv4_detail_snapshot(),
210207
"os_version": _get_os_version(),
211208
"agent_version": AGENT_VERSION,
212-
# Keep legacy key for backward compatibility with old teacher builds.
213-
"version": AGENT_VERSION,
214209
"token": self.token,
215210
},
216211
)

0 commit comments

Comments
 (0)