start_proxy.py 15 KB

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