start_proxy.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Proxy Service Starter (Mihomo Multi-Port Proxy Manager)
  5. 启动本地 Mihomo 多端口代理服务脚本。
  6. 功能:
  7. - 自动识别当前操作系统并定位 downloads/ 目录下的 mihomo 二进制程序
  8. - 自动检测并加载 config/mihomo_config.yaml (或 local_multi_port.yaml)
  9. - 启动前自动测试配置合法性 (-t)
  10. - 支持前台运行 (Ctrl+C 优雅退出) 与后台运行 (--daemon / -d)
  11. - 支持状态检查 (--status) 与后台停止 (--stop)
  12. """
  13. import os
  14. import sys
  15. import glob
  16. import time
  17. import signal
  18. import socket
  19. import argparse
  20. import platform
  21. import subprocess
  22. import yaml
  23. # 强制标准输出使用 UTF-8
  24. if sys.platform == "win32":
  25. try:
  26. sys.stdout.reconfigure(encoding="utf-8", errors="replace")
  27. sys.stderr.reconfigure(encoding="utf-8", errors="replace")
  28. except Exception:
  29. pass
  30. PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
  31. LOG_DIR = os.path.join(PROJECT_ROOT, "logs")
  32. PID_FILE = os.path.join(LOG_DIR, "mihomo.pid")
  33. DEFAULT_LOG_FILE = os.path.join(LOG_DIR, "mihomo.log")
  34. def find_mihomo_bin(custom_path=None):
  35. """查找可用的 mihomo 二进制程序路径"""
  36. custom_path = custom_path or os.environ.get("MIHOMO_BIN")
  37. if custom_path:
  38. abs_p = os.path.abspath(custom_path)
  39. if os.path.isfile(abs_p):
  40. return abs_p
  41. import shutil
  42. which_p = shutil.which(custom_path)
  43. if which_p and os.path.isfile(which_p):
  44. return which_p
  45. current_os = platform.system().lower()
  46. downloads_dir = os.path.join(PROJECT_ROOT, "downloads")
  47. candidates = []
  48. if current_os == "windows":
  49. candidates.extend([
  50. os.path.join(downloads_dir, "mihomo-windows-amd64-v3.exe"),
  51. os.path.join(downloads_dir, "mihomo-windows-amd64.exe"),
  52. os.path.join(downloads_dir, "mihomo.exe"),
  53. ])
  54. for f in glob.glob(os.path.join(downloads_dir, "*mihomo*.exe")):
  55. candidates.append(f)
  56. elif current_os == "darwin":
  57. candidates.extend([
  58. os.path.join(downloads_dir, "mihomo-darwin"),
  59. os.path.join(downloads_dir, "mihomo"),
  60. ])
  61. for f in glob.glob(os.path.join(downloads_dir, "*mihomo*")):
  62. if not f.endswith((".gz", ".zip", ".tar.gz", ".tmp")):
  63. candidates.append(f)
  64. else: # linux
  65. candidates.extend([
  66. "/bin/mihomo",
  67. "/usr/bin/mihomo",
  68. "/usr/local/bin/mihomo",
  69. os.path.join(downloads_dir, "mihomo-linux"),
  70. os.path.join(downloads_dir, "mihomo"),
  71. ])
  72. for f in glob.glob(os.path.join(downloads_dir, "*mihomo*")):
  73. if not f.endswith((".gz", ".zip", ".tar.gz", ".tmp")):
  74. candidates.append(f)
  75. for c in candidates:
  76. if os.path.isfile(c) and not c.endswith((".gz", ".zip", ".tar.gz", ".tmp")):
  77. # 确保 Linux/Mac 有可执行权限
  78. if current_os != "windows" and not os.access(c, os.X_OK):
  79. try:
  80. os.chmod(c, 0o755)
  81. except Exception:
  82. pass
  83. return os.path.abspath(c)
  84. # 兜底:环境变量 PATH 中查找
  85. import shutil
  86. which_bin = shutil.which("mihomo")
  87. if which_bin:
  88. return which_bin
  89. return None
  90. def find_config_file(custom_path=None):
  91. """查找配置文件路径"""
  92. if custom_path:
  93. abs_p = os.path.abspath(custom_path)
  94. if os.path.isfile(abs_p):
  95. return abs_p
  96. # 兼容相对路径从 config/ 查找
  97. p_in_config = os.path.join(PROJECT_ROOT, "config", os.path.basename(custom_path))
  98. if os.path.isfile(p_in_config):
  99. return p_in_config
  100. # 兼容旧名称 local_multi_port.yaml 自动映射到 mihomo_config.yaml
  101. if "local_multi_port.yaml" in custom_path:
  102. p_mihomo = os.path.join(PROJECT_ROOT, "config", "mihomo_config.yaml")
  103. if os.path.isfile(p_mihomo):
  104. return p_mihomo
  105. raise FileNotFoundError(f"指定的配置文件不存在: {custom_path}")
  106. # 默认路径
  107. paths = [
  108. os.path.join(PROJECT_ROOT, "config", "mihomo_config.yaml"),
  109. os.path.join(PROJECT_ROOT, "config", "local_multi_port.yaml"),
  110. ]
  111. for p in paths:
  112. if os.path.isfile(p):
  113. return p
  114. return paths[0]
  115. def is_port_listening(host="127.0.0.1", port=10000, timeout=1.0):
  116. """检查指定端口是否已在监听"""
  117. try:
  118. with socket.create_connection((host, int(port)), timeout=timeout):
  119. return True
  120. except (socket.timeout, ConnectionRefusedError, OSError):
  121. return False
  122. def test_config(bin_path, config_path):
  123. """调用 mihomo -t -f 校验配置语法"""
  124. cmd = [bin_path, "-t", "-f", config_path]
  125. res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
  126. if res.returncode != 0:
  127. print(f"❌ 配置文件校验失败: {res.stderr or res.stdout}")
  128. return False
  129. return True
  130. def get_process_by_pid(pid):
  131. """检查 PID 对应的进程是否存在"""
  132. if pid <= 0:
  133. return False
  134. if sys.platform == "win32":
  135. try:
  136. res = subprocess.run(
  137. ["tasklist", "/FI", f"PID eq {pid}", "/NH"],
  138. capture_output=True,
  139. text=True
  140. )
  141. return str(pid) in res.stdout
  142. except Exception:
  143. return False
  144. else:
  145. try:
  146. os.kill(pid, 0)
  147. return True
  148. except OSError:
  149. return False
  150. def stop_service():
  151. """停止后台运行的 mihomo 代理服务"""
  152. if not os.path.exists(PID_FILE):
  153. print("ℹ️ 未发现运行中的 PID 文件。")
  154. return
  155. try:
  156. with open(PID_FILE, "r", encoding="utf-8") as f:
  157. pid = int(f.read().strip())
  158. except Exception:
  159. print("❌ 无法读取 PID 文件。")
  160. return
  161. if not get_process_by_pid(pid):
  162. print(f"ℹ️ PID {pid} 不存在,清理失效的 PID 文件。")
  163. try:
  164. os.remove(PID_FILE)
  165. except Exception:
  166. pass
  167. return
  168. print(f"[*] 正在终止 Mihomo 进程 (PID: {pid})...")
  169. if sys.platform == "win32":
  170. subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)], capture_output=True)
  171. else:
  172. try:
  173. os.kill(pid, signal.SIGTERM)
  174. time.sleep(1)
  175. if get_process_by_pid(pid):
  176. os.kill(pid, signal.SIGKILL)
  177. except Exception as e:
  178. print(f"终止进程出错: {e}")
  179. try:
  180. os.remove(PID_FILE)
  181. except Exception:
  182. pass
  183. print("✅ Mihomo 代理服务已停止。")
  184. def check_status(config_path):
  185. """检查代理服务状态"""
  186. is_pid_alive = False
  187. pid = None
  188. if os.path.exists(PID_FILE):
  189. try:
  190. with open(PID_FILE, "r", encoding="utf-8") as f:
  191. pid = int(f.read().strip())
  192. is_pid_alive = get_process_by_pid(pid)
  193. except Exception:
  194. pass
  195. # 解析配置查看核心监听端口
  196. mixed_port = 10000
  197. first_listener_port = None
  198. if os.path.isfile(config_path):
  199. try:
  200. with open(config_path, "r", encoding="utf-8") as f:
  201. data = yaml.safe_load(f) or {}
  202. mixed_port = data.get("mixed-port", 10000)
  203. listeners = data.get("listeners", [])
  204. if listeners:
  205. first_listener_port = listeners[0].get("port")
  206. except Exception:
  207. pass
  208. port_ok = is_port_listening("127.0.0.1", mixed_port)
  209. listener_ok = is_port_listening("127.0.0.1", first_listener_port) if first_listener_port else False
  210. print("\n📊 代理服务状态检查:")
  211. print("-" * 50)
  212. print(f"PID 文件状态: {'运行中 (PID ' + str(pid) + ')' if is_pid_alive else '未记录或未运行'}")
  213. print(f"Mixed-Port ({mixed_port}): {'🟢 正在监听' if port_ok else '🔴 未监听'}")
  214. if first_listener_port:
  215. print(f"节点端口 ({first_listener_port}): {'🟢 正在监听' if listener_ok else '🔴 未监听'}")
  216. print("-" * 50)
  217. if port_ok or is_pid_alive:
  218. print("✅ 代理服务正常运行中。")
  219. else:
  220. print("⚪ 代理服务当前未运行。")
  221. def check_health(config_path):
  222. """用于 Docker HEALTHCHECK / 容器就绪探测的健康检查 (就绪返回码 0,未就绪返回 1)"""
  223. mixed_port = 10000
  224. if os.path.isfile(config_path):
  225. try:
  226. with open(config_path, "r", encoding="utf-8") as f:
  227. data = yaml.safe_load(f) or {}
  228. mixed_port = data.get("mixed-port", 10000)
  229. except Exception:
  230. pass
  231. if is_port_listening("127.0.0.1", mixed_port, timeout=1.5):
  232. print(f"OK - Proxy is healthy (Mixed-Port {mixed_port} listening)", flush=True)
  233. sys.exit(0)
  234. else:
  235. print(f"FAIL - Proxy is not ready (Mixed-Port {mixed_port} not listening)", file=sys.stderr, flush=True)
  236. sys.exit(1)
  237. def start_service(args):
  238. """启动代理服务"""
  239. bin_path = find_mihomo_bin(args.bin)
  240. if not bin_path:
  241. print("❌ 未在 downloads/ 目录或系统中找到 mihomo 二进制程序!")
  242. print("👉 请先运行: python scripts/download_deps.py 下载所需依赖。")
  243. sys.exit(1)
  244. config_path = find_config_file(args.config)
  245. if not os.path.isfile(config_path):
  246. print(f"❌ 未找到配置文件: {config_path}")
  247. print("👉 请先运行: python tools/generate_clash_multi_port.py 生成配置。")
  248. sys.exit(1)
  249. print(f"[*] Mihomo 程序: {bin_path}", flush=True)
  250. print(f"[*] 配置文件路径: {config_path}", flush=True)
  251. # 自动适配 Docker / 外部连接:确保 allow-lan 开启
  252. allow_lan_env = os.getenv("ALLOW_LAN", "").lower() in ("1", "true", "yes")
  253. in_docker = os.path.exists("/.dockerenv") or os.getenv("DOCKER_CONTAINER") == "true"
  254. if getattr(args, "allow_lan", False) or allow_lan_env or in_docker:
  255. try:
  256. with open(config_path, "r", encoding="utf-8") as f:
  257. content = f.read()
  258. if "allow-lan: false" in content:
  259. print("[*] 正在为容器/局域网环境自动修正 allow-lan: true ...", flush=True)
  260. content = content.replace("allow-lan: false", "allow-lan: true")
  261. with open(config_path, "w", encoding="utf-8") as f:
  262. f.write(content)
  263. except Exception as e:
  264. print(f"⚠️ 自动配置 allow-lan 提示: {e}", flush=True)
  265. # 读取配置概要
  266. try:
  267. with open(config_path, "r", encoding="utf-8") as f:
  268. cfg = yaml.safe_load(f) or {}
  269. proxies_cnt = len(cfg.get("proxies", []))
  270. listeners = cfg.get("listeners", [])
  271. mixed_port = cfg.get("mixed-port", 10000)
  272. ports = [l.get("port") for l in listeners if "port" in l]
  273. port_range_str = f"{min(ports)} ~ {max(ports)}" if ports else "无"
  274. print(f"[*] 节点总数: {proxies_cnt} | 独立监听端口数: {len(listeners)} ({port_range_str}) | 全局 Mixed-Port: {mixed_port}")
  275. except Exception as e:
  276. print(f"⚠️ 解析配置文件概要提示: {e}")
  277. # 预检配置有效性
  278. print("[*] 正在校验配置文件语法...")
  279. if not test_config(bin_path, config_path):
  280. sys.exit(1)
  281. print("✅ 配置文件语法校验通过!")
  282. # 检查端口是否已被占用
  283. if is_port_listening("127.0.0.1", mixed_port):
  284. print(f"⚠️ 警告: 端口 {mixed_port} 已经被占用!可能已有 Mihomo 进程在运行。")
  285. if args.daemon:
  286. print("若需重启请先执行: python start_proxy.py --stop")
  287. sys.exit(1)
  288. os.makedirs(LOG_DIR, exist_ok=True)
  289. cmd = [bin_path, "-f", config_path]
  290. # 后台守护进程模式
  291. if args.daemon:
  292. log_file = args.log_file or DEFAULT_LOG_FILE
  293. print(f"[*] 正在启动后台代理守护服务,日志写入: {log_file}")
  294. with open(log_file, "a", encoding="utf-8") as out:
  295. p = subprocess.Popen(
  296. cmd,
  297. stdout=out,
  298. stderr=out,
  299. cwd=PROJECT_ROOT,
  300. creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0
  301. )
  302. with open(PID_FILE, "w", encoding="utf-8") as f:
  303. f.write(str(p.pid))
  304. # 检查是否成功启动并监听
  305. time.sleep(1.5)
  306. if is_port_listening("127.0.0.1", mixed_port):
  307. print(f"✅ Mihomo 代理服务已在后台成功启动!(PID: {p.pid})")
  308. print(f" 查看运行状态: python start_proxy.py --status")
  309. print(f" 停止代理服务: python start_proxy.py --stop")
  310. else:
  311. print(f"⚠️ 服务已启动 (PID: {p.pid}),但端口尚未就绪,请查看日志: {log_file}")
  312. return
  313. # 前台运行模式 (Ctrl+C 退出)
  314. print("\n" + "=" * 60)
  315. print("🚀 正在前台启动 Mihomo 多端口代理服务...")
  316. print("💡 按 Ctrl + C 可安全停止服务")
  317. print("=" * 60 + "\n")
  318. p = subprocess.Popen(cmd, cwd=PROJECT_ROOT)
  319. def handle_sigint(signum, frame):
  320. print("\n[*] 正在关闭 Mihomo 代理服务...")
  321. p.terminate()
  322. try:
  323. p.wait(timeout=3)
  324. except subprocess.TimeoutExpired:
  325. p.kill()
  326. print("✅ Mihomo 代理服务已安全退出。")
  327. sys.exit(0)
  328. signal.signal(signal.SIGINT, handle_sigint)
  329. if hasattr(signal, "SIGTERM"):
  330. signal.signal(signal.SIGTERM, handle_sigint)
  331. try:
  332. p.wait()
  333. except KeyboardInterrupt:
  334. handle_sigint(None, None)
  335. def main():
  336. parser = argparse.ArgumentParser(
  337. description="Mihomo 多端口代理服务管理脚本",
  338. formatter_class=argparse.RawDescriptionHelpFormatter,
  339. epilog="""示例用法:
  340. python start_proxy.py # 默认前台启动 (Ctrl+C 停止)
  341. python start_proxy.py -d # 后台守护模式运行
  342. python start_proxy.py --status # 查看当前代理服务运行状态
  343. python start_proxy.py --stop # 停止后台代理服务
  344. python start_proxy.py -f config/mihomo_config.yaml # 指定配置文件
  345. """
  346. )
  347. parser.add_argument("-f", "--config", type=str, default=None, help="Mihomo 配置文件路径 (默认: config/mihomo_config.yaml)")
  348. parser.add_argument("--bin", type=str, default=None, help="Mihomo 可执行程序路径 (默认自动查找 downloads/ 目录)")
  349. parser.add_argument("-d", "--daemon", action="store_true", help="后台运行模式")
  350. parser.add_argument("--log-file", type=str, default=None, help="后台运行日志输出文件 (默认: logs/mihomo.log)")
  351. parser.add_argument("--status", action="store_true", help="检查代理服务运行状态")
  352. parser.add_argument("--stop", action="store_true", help="停止后台代理服务")
  353. parser.add_argument("--check-health", action="store_true", help="检查服务端口健康状态 (正常监听返回 0,未就绪返回 1)")
  354. parser.add_argument("--allow-lan", action="store_true", help="强制确保 allow-lan 开启 (允许局域网/跨主机访问)")
  355. args = parser.parse_args()
  356. if args.check_health:
  357. config_path = find_config_file(args.config)
  358. check_health(config_path)
  359. return
  360. if args.stop:
  361. stop_service()
  362. return
  363. if args.status:
  364. config_path = find_config_file(args.config)
  365. check_status(config_path)
  366. return
  367. start_service(args)
  368. if __name__ == "__main__":
  369. main()