| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- Proxy Service Starter (Mihomo Multi-Port Proxy Manager)
- 启动本地 Mihomo 多端口代理服务脚本。
- 功能:
- - 自动识别当前操作系统并定位 downloads/ 目录下的 mihomo 二进制程序
- - 自动检测并加载 config/mihomo_config.yaml (或 local_multi_port.yaml)
- - 启动前自动测试配置合法性 (-t)
- - 支持前台运行 (Ctrl+C 优雅退出) 与后台运行 (--daemon / -d)
- - 支持状态检查 (--status) 与后台停止 (--stop)
- """
- import os
- import sys
- import glob
- import time
- import signal
- import socket
- import argparse
- import platform
- import subprocess
- import yaml
- # 强制标准输出使用 UTF-8
- if sys.platform == "win32":
- try:
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
- sys.stderr.reconfigure(encoding="utf-8", errors="replace")
- except Exception:
- pass
- PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
- LOG_DIR = os.path.join(PROJECT_ROOT, "logs")
- PID_FILE = os.path.join(LOG_DIR, "mihomo.pid")
- DEFAULT_LOG_FILE = os.path.join(LOG_DIR, "mihomo.log")
- def find_mihomo_bin(custom_path=None):
- """查找可用的 mihomo 二进制程序路径"""
- custom_path = custom_path or os.environ.get("MIHOMO_BIN")
- if custom_path:
- abs_p = os.path.abspath(custom_path)
- if os.path.isfile(abs_p):
- return abs_p
- import shutil
- which_p = shutil.which(custom_path)
- if which_p and os.path.isfile(which_p):
- return which_p
- current_os = platform.system().lower()
- downloads_dir = os.path.join(PROJECT_ROOT, "downloads")
- candidates = []
- if current_os == "windows":
- candidates.extend([
- os.path.join(downloads_dir, "mihomo-windows-amd64-v3.exe"),
- os.path.join(downloads_dir, "mihomo-windows-amd64.exe"),
- os.path.join(downloads_dir, "mihomo.exe"),
- ])
- for f in glob.glob(os.path.join(downloads_dir, "*mihomo*.exe")):
- candidates.append(f)
- elif current_os == "darwin":
- candidates.extend([
- os.path.join(downloads_dir, "mihomo-darwin"),
- os.path.join(downloads_dir, "mihomo"),
- ])
- for f in glob.glob(os.path.join(downloads_dir, "*mihomo*")):
- if not f.endswith((".gz", ".zip", ".tar.gz", ".tmp")):
- candidates.append(f)
- else: # linux
- candidates.extend([
- "/bin/mihomo",
- "/usr/bin/mihomo",
- "/usr/local/bin/mihomo",
- os.path.join(downloads_dir, "mihomo-linux"),
- os.path.join(downloads_dir, "mihomo"),
- ])
- for f in glob.glob(os.path.join(downloads_dir, "*mihomo*")):
- if not f.endswith((".gz", ".zip", ".tar.gz", ".tmp")):
- candidates.append(f)
- for c in candidates:
- if os.path.isfile(c) and not c.endswith((".gz", ".zip", ".tar.gz", ".tmp")):
- # 确保 Linux/Mac 有可执行权限
- if current_os != "windows" and not os.access(c, os.X_OK):
- try:
- os.chmod(c, 0o755)
- except Exception:
- pass
- return os.path.abspath(c)
- # 兜底:环境变量 PATH 中查找
- import shutil
- which_bin = shutil.which("mihomo")
- if which_bin:
- return which_bin
- return None
- def find_config_file(custom_path=None):
- """查找配置文件路径"""
- if custom_path:
- abs_p = os.path.abspath(custom_path)
- if os.path.isfile(abs_p):
- return abs_p
- # 兼容相对路径从 config/ 查找
- p_in_config = os.path.join(PROJECT_ROOT, "config", os.path.basename(custom_path))
- if os.path.isfile(p_in_config):
- return p_in_config
- # 兼容旧名称 local_multi_port.yaml 自动映射到 mihomo_config.yaml
- if "local_multi_port.yaml" in custom_path:
- p_mihomo = os.path.join(PROJECT_ROOT, "config", "mihomo_config.yaml")
- if os.path.isfile(p_mihomo):
- return p_mihomo
- raise FileNotFoundError(f"指定的配置文件不存在: {custom_path}")
- # 默认路径
- paths = [
- os.path.join(PROJECT_ROOT, "config", "mihomo_config.yaml"),
- os.path.join(PROJECT_ROOT, "config", "local_multi_port.yaml"),
- ]
- for p in paths:
- if os.path.isfile(p):
- return p
- return paths[0]
- def is_port_listening(host="127.0.0.1", port=10000, timeout=1.0):
- """检查指定端口是否已在监听"""
- try:
- with socket.create_connection((host, int(port)), timeout=timeout):
- return True
- except (socket.timeout, ConnectionRefusedError, OSError):
- return False
- def test_config(bin_path, config_path):
- """调用 mihomo -t -f 校验配置语法"""
- cmd = [bin_path, "-t", "-f", config_path]
- res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
- if res.returncode != 0:
- print(f"❌ 配置文件校验失败: {res.stderr or res.stdout}")
- return False
- return True
- def get_process_by_pid(pid):
- """检查 PID 对应的进程是否存在"""
- if pid <= 0:
- return False
- if sys.platform == "win32":
- try:
- res = subprocess.run(
- ["tasklist", "/FI", f"PID eq {pid}", "/NH"],
- capture_output=True,
- text=True
- )
- return str(pid) in res.stdout
- except Exception:
- return False
- else:
- try:
- os.kill(pid, 0)
- return True
- except OSError:
- return False
- def stop_service():
- """停止后台运行的 mihomo 代理服务"""
- if not os.path.exists(PID_FILE):
- print("ℹ️ 未发现运行中的 PID 文件。")
- return
- try:
- with open(PID_FILE, "r", encoding="utf-8") as f:
- pid = int(f.read().strip())
- except Exception:
- print("❌ 无法读取 PID 文件。")
- return
- if not get_process_by_pid(pid):
- print(f"ℹ️ PID {pid} 不存在,清理失效的 PID 文件。")
- try:
- os.remove(PID_FILE)
- except Exception:
- pass
- return
- print(f"[*] 正在终止 Mihomo 进程 (PID: {pid})...")
- if sys.platform == "win32":
- subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)], capture_output=True)
- else:
- try:
- os.kill(pid, signal.SIGTERM)
- time.sleep(1)
- if get_process_by_pid(pid):
- os.kill(pid, signal.SIGKILL)
- except Exception as e:
- print(f"终止进程出错: {e}")
- try:
- os.remove(PID_FILE)
- except Exception:
- pass
- print("✅ Mihomo 代理服务已停止。")
- def check_status(config_path):
- """检查代理服务状态"""
- is_pid_alive = False
- pid = None
- if os.path.exists(PID_FILE):
- try:
- with open(PID_FILE, "r", encoding="utf-8") as f:
- pid = int(f.read().strip())
- is_pid_alive = get_process_by_pid(pid)
- except Exception:
- pass
- # 解析配置查看核心监听端口
- mixed_port = 10000
- first_listener_port = None
- if os.path.isfile(config_path):
- try:
- with open(config_path, "r", encoding="utf-8") as f:
- data = yaml.safe_load(f) or {}
- mixed_port = data.get("mixed-port", 10000)
- listeners = data.get("listeners", [])
- if listeners:
- first_listener_port = listeners[0].get("port")
- except Exception:
- pass
- port_ok = is_port_listening("127.0.0.1", mixed_port)
- listener_ok = is_port_listening("127.0.0.1", first_listener_port) if first_listener_port else False
- print("\n📊 代理服务状态检查:")
- print("-" * 50)
- print(f"PID 文件状态: {'运行中 (PID ' + str(pid) + ')' if is_pid_alive else '未记录或未运行'}")
- print(f"Mixed-Port ({mixed_port}): {'🟢 正在监听' if port_ok else '🔴 未监听'}")
- if first_listener_port:
- print(f"节点端口 ({first_listener_port}): {'🟢 正在监听' if listener_ok else '🔴 未监听'}")
- print("-" * 50)
- if port_ok or is_pid_alive:
- print("✅ 代理服务正常运行中。")
- else:
- print("⚪ 代理服务当前未运行。")
- def check_health(config_path):
- """用于 Docker HEALTHCHECK / 容器就绪探测的健康检查 (就绪返回码 0,未就绪返回 1)"""
- mixed_port = 10000
- if os.path.isfile(config_path):
- try:
- with open(config_path, "r", encoding="utf-8") as f:
- data = yaml.safe_load(f) or {}
- mixed_port = data.get("mixed-port", 10000)
- except Exception:
- pass
- if is_port_listening("127.0.0.1", mixed_port, timeout=1.5):
- print(f"OK - Proxy is healthy (Mixed-Port {mixed_port} listening)", flush=True)
- sys.exit(0)
- else:
- print(f"FAIL - Proxy is not ready (Mixed-Port {mixed_port} not listening)", file=sys.stderr, flush=True)
- sys.exit(1)
- def start_service(args):
- """启动代理服务"""
- bin_path = find_mihomo_bin(args.bin)
- if not bin_path:
- print("❌ 未在 downloads/ 目录或系统中找到 mihomo 二进制程序!")
- print("👉 请先运行: python download_deps.py 下载所需依赖。")
- sys.exit(1)
- config_path = find_config_file(args.config)
- if not os.path.isfile(config_path):
- print(f"❌ 未找到配置文件: {config_path}")
- print("👉 请先运行: python tools/generate_clash_multi_port.py 生成配置。")
- sys.exit(1)
- print(f"[*] Mihomo 程序: {bin_path}", flush=True)
- print(f"[*] 配置文件路径: {config_path}", flush=True)
- # 自动适配 Docker / 外部连接:确保 allow-lan 开启
- allow_lan_env = os.getenv("ALLOW_LAN", "").lower() in ("1", "true", "yes")
- in_docker = os.path.exists("/.dockerenv") or os.getenv("DOCKER_CONTAINER") == "true"
- if getattr(args, "allow_lan", False) or allow_lan_env or in_docker:
- try:
- with open(config_path, "r", encoding="utf-8") as f:
- content = f.read()
- if "allow-lan: false" in content:
- print("[*] 正在为容器/局域网环境自动修正 allow-lan: true ...", flush=True)
- content = content.replace("allow-lan: false", "allow-lan: true")
- with open(config_path, "w", encoding="utf-8") as f:
- f.write(content)
- except Exception as e:
- print(f"⚠️ 自动配置 allow-lan 提示: {e}", flush=True)
- # 读取配置概要
- try:
- with open(config_path, "r", encoding="utf-8") as f:
- cfg = yaml.safe_load(f) or {}
- proxies_cnt = len(cfg.get("proxies", []))
- listeners = cfg.get("listeners", [])
- mixed_port = cfg.get("mixed-port", 10000)
- ports = [l.get("port") for l in listeners if "port" in l]
- port_range_str = f"{min(ports)} ~ {max(ports)}" if ports else "无"
- print(f"[*] 节点总数: {proxies_cnt} | 独立监听端口数: {len(listeners)} ({port_range_str}) | 全局 Mixed-Port: {mixed_port}")
- except Exception as e:
- print(f"⚠️ 解析配置文件概要提示: {e}")
- # 预检配置有效性
- print("[*] 正在校验配置文件语法...")
- if not test_config(bin_path, config_path):
- sys.exit(1)
- print("✅ 配置文件语法校验通过!")
- # 检查端口是否已被占用
- if is_port_listening("127.0.0.1", mixed_port):
- print(f"⚠️ 警告: 端口 {mixed_port} 已经被占用!可能已有 Mihomo 进程在运行。")
- if args.daemon:
- print("若需重启请先执行: python start_proxy.py --stop")
- sys.exit(1)
- os.makedirs(LOG_DIR, exist_ok=True)
- cmd = [bin_path, "-f", config_path]
- # 后台守护进程模式
- if args.daemon:
- log_file = args.log_file or DEFAULT_LOG_FILE
- print(f"[*] 正在启动后台代理守护服务,日志写入: {log_file}")
- with open(log_file, "a", encoding="utf-8") as out:
- p = subprocess.Popen(
- cmd,
- stdout=out,
- stderr=out,
- cwd=PROJECT_ROOT,
- creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == "win32" else 0
- )
- with open(PID_FILE, "w", encoding="utf-8") as f:
- f.write(str(p.pid))
- # 检查是否成功启动并监听
- time.sleep(1.5)
- if is_port_listening("127.0.0.1", mixed_port):
- print(f"✅ Mihomo 代理服务已在后台成功启动!(PID: {p.pid})")
- print(f" 查看运行状态: python start_proxy.py --status")
- print(f" 停止代理服务: python start_proxy.py --stop")
- else:
- print(f"⚠️ 服务已启动 (PID: {p.pid}),但端口尚未就绪,请查看日志: {log_file}")
- return
- # 前台运行模式 (Ctrl+C 退出)
- print("\n" + "=" * 60)
- print("🚀 正在前台启动 Mihomo 多端口代理服务...")
- print("💡 按 Ctrl + C 可安全停止服务")
- print("=" * 60 + "\n")
- p = subprocess.Popen(cmd, cwd=PROJECT_ROOT)
- def handle_sigint(signum, frame):
- print("\n[*] 正在关闭 Mihomo 代理服务...")
- p.terminate()
- try:
- p.wait(timeout=3)
- except subprocess.TimeoutExpired:
- p.kill()
- print("✅ Mihomo 代理服务已安全退出。")
- sys.exit(0)
- signal.signal(signal.SIGINT, handle_sigint)
- if hasattr(signal, "SIGTERM"):
- signal.signal(signal.SIGTERM, handle_sigint)
- try:
- p.wait()
- except KeyboardInterrupt:
- handle_sigint(None, None)
- def main():
- parser = argparse.ArgumentParser(
- description="Mihomo 多端口代理服务管理脚本",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""示例用法:
- python start_proxy.py # 默认前台启动 (Ctrl+C 停止)
- python start_proxy.py -d # 后台守护模式运行
- python start_proxy.py --status # 查看当前代理服务运行状态
- python start_proxy.py --stop # 停止后台代理服务
- python start_proxy.py -f config/mihomo_config.yaml # 指定配置文件
- """
- )
- parser.add_argument("-f", "--config", type=str, default=None, help="Mihomo 配置文件路径 (默认: config/mihomo_config.yaml)")
- parser.add_argument("--bin", type=str, default=None, help="Mihomo 可执行程序路径 (默认自动查找 downloads/ 目录)")
- parser.add_argument("-d", "--daemon", action="store_true", help="后台运行模式")
- parser.add_argument("--log-file", type=str, default=None, help="后台运行日志输出文件 (默认: logs/mihomo.log)")
- parser.add_argument("--status", action="store_true", help="检查代理服务运行状态")
- parser.add_argument("--stop", action="store_true", help="停止后台代理服务")
- parser.add_argument("--check-health", action="store_true", help="检查服务端口健康状态 (正常监听返回 0,未就绪返回 1)")
- parser.add_argument("--allow-lan", action="store_true", help="强制确保 allow-lan 开启 (允许局域网/跨主机访问)")
- args = parser.parse_args()
- if args.check_health:
- config_path = find_config_file(args.config)
- check_health(config_path)
- return
- if args.stop:
- stop_service()
- return
- if args.status:
- config_path = find_config_file(args.config)
- check_status(config_path)
- return
- start_service(args)
- if __name__ == "__main__":
- main()
|