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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
| apt install python3 -y
cat > /opt/mihomo_panel.py << 'PYEOF'
import http.server, socketserver, subprocess, json, base64, sys
PORT = 8099 USER = "admin" PASS = "223admin" CONFIG_PATH = "/root/.config/mihomo/config.yaml" MIHOMO_SERVICE = "mihomo" AUTH = "Basic " + base64.b64encode(f"{USER}:{PASS}".encode()).decode()
HTML = '''<!DOCTYPE html><html lang=zh-CN><head><meta charset=UTF-8> <meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <title>mihomo 代理控制</title> <style> *{margin:0;padding:0;box-sizing:border-box} body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;background:#0d1117;color:#c9d1d9;min-height:100vh} .header{padding:16px;background:#161b22;border-bottom:1px solid #30363d;position:sticky;top:0;z-index:10} .header h1{font-size:18px;color:#58a6ff;margin-bottom:4px} .header .status{font-size:13px;color:#8b949e} .dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px} .dot.green{background:#3fb950;box-shadow:0 0 6px #3fb950} .dot.red{background:#f85149} .container{padding:12px;max-width:600px;margin:0 auto} .card{background:#161b22;border:1px solid #30363d;border-radius:10px;margin-bottom:12px;overflow:hidden} .card-title{padding:10px 14px;font:600 13px/1 sans-serif;color:#8b949e;background:#0d1117;border-bottom:1px solid #30363d} .card-body{padding:14px} .btn{display:block;width:100%;padding:14px;margin-bottom:8px;border:none;border-radius:8px;font-size:15px;font-weight:600;cursor:pointer;transition:.15s} .btn:active{transform:scale(.97)} .btn-green{background:#238636;color:#fff} .btn-red{background:#da3633;color:#fff} .btn-orange{background:#d29922;color:#000} .btn-gray{background:#21262d;color:#c9d1d9;border:1px solid #30363d} .btn-row{display:flex;gap:8px} .btn-row .btn{margin-bottom:0} .info-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:8px} .info-item{background:#0d1117;border-radius:6px;padding:10px} .info-item .label{font-size:11px;color:#8b949e;margin-bottom:4px} .info-item .value{font-size:14px;font-weight:600;color:#f0f6fc;font-family:monospace} textarea{width:100%;height:280px;background:#0d1117;border:1px solid #30363d;border-radius:6px;color:#c9d1d9;font-family:monospace;font-size:12px;padding:12px;resize:vertical} .save-row{display:flex;gap:8px;margin-top:8px} .save-row .btn{margin-bottom:0} .log-box{width:100%;height:120px;background:#0d1117;border:1px solid #30363d;border-radius:6px;color:#8b949e;font-family:monospace;font-size:11px;padding:10px;overflow-y:auto;margin-bottom:8px;white-space:pre-wrap} .toast{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);background:#238636;color:#fff;padding:10px 20px;border-radius:8px;font-size:14px;z-index:100;opacity:0;transition:.3s;pointer-events:none} .toast.show{opacity:1} .toast.err{background:#da3633} </style></head> <body> <div class="header"> <h1>mihomo 代理控制</h1> <div class="status"><span class="dot" id="statusDot"></span><span id="statusText">检测中...</span></div> </div> <div class="container"> <div class="card"> <div class="card-title">服务控制</div> <div class="card-body"> <div class="btn-row"> <button class="btn btn-green" onclick="action('start')">启动</button> <button class="btn btn-red" onclick="action('stop')">停止</button> </div> <button class="btn btn-orange" onclick="action('restart')">重启 mihomo</button> <button class="btn btn-gray" onclick="action('reboot')">重启服务器</button> </div> </div> <div class="card"> <div class="card-title">运行状态</div> <div class="card-body"> <div class="info-grid"> <div class="info-item"><div class="label">代理端口</div><div class="value">7890</div></div> <div class="info-item"><div class="label">DNS端口</div><div class="value">1053</div></div> <div class="info-item"><div class="label">控制端口</div><div class="value">9090</div></div> <div class="info-item"><div class="label">面板端口</div><div class="value">8099</div></div> </div> </div> </div> <div class="card"> <div class="card-title">配置编辑</div> <div class="card-body"> <textarea id="config"></textarea> <div class="save-row"> <button class="btn btn-green" onclick="saveConfig()">保存并重启</button> <button class="btn btn-gray" onclick="loadConfig()">重新加载</button> </div> </div> </div> <div class="card"> <div class="card-title">日志</div> <div class="card-body"> <div class="log-box" id="logBox">点击加载日志</div> <button class="btn btn-gray" onclick="loadLog()">加载日志</button> </div> </div> </div> <div class="toast" id="toast"></div> <script> var H={"Content-Type":"application/json","Authorization":"AUTH_PLACEHOLDER"}; function $(i){return document.getElementById(i)} function toast(m,e){ var t=$("toast");t.textContent=m;t.className="toast show"+(e?" err":""); setTimeout(function(){t.className="toast"},3000) } async function action(c){ if(c==="reboot"&&!confirm("确定重启服务器?"))return; var r=await fetch("/api/"+c,{method:"POST",headers:H}); var d=await r.json(); toast(d.ok?d.msg:"失败:"+(d.msg||"未知错误"),!d.ok); setTimeout(checkStatus,1500); } async function checkStatus(){ try{ var r=await fetch("/api/status",{headers:H}); var d=await r.json(); $("statusDot").className=d.active?"dot green":"dot red"; $("statusText").textContent=d.active?"运行中 PID "+d.pid:"已停止"; }catch(e){} } async function loadConfig(){ try{ var d=await(await fetch("/api/config",{headers:H})).json(); $("config").value=d.content||""; }catch(e){toast("加载失败",1)} } async function saveConfig(){ var c=$("config").value; try{ var d=await(await fetch("/api/config",{method:"POST",headers:H,body:JSON.stringify({content:c})})).json(); toast(d.ok?"保存成功并已重启":"保存失败",!d.ok); }catch(e){toast("保存失败",1)} } async function loadLog(){ try{ var d=await(await fetch("/api/log",{headers:H})).json(); $("logBox").textContent=d.content||"无日志"; }catch(e){toast("日志加载失败",1)} } checkStatus();loadConfig(); </script> </body></html>'''.replace("AUTH_PLACEHOLDER", AUTH)
def run_cmd(cmd, timeout=15): try: r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) return {"ok": r.returncode == 0, "msg": r.stdout.strip() or r.stderr.strip()} except: return {"ok": False, "msg": "命令执行失败"}
def set_freellmapi_proxy(proxy_url): """自动同步 FreeLLMAPI 代理设置(启动mihomo时设代理,停止时清空直连)""" try: import sqlite3 db = "/opt/freellmapi/server/data/freeapi.db" conn = sqlite3.connect(db) cur = conn.cursor() cur.execute("UPDATE settings SET value=? WHERE key='proxy_url'", (proxy_url,)) if cur.rowcount == 0: cur.execute("INSERT INTO settings (key, value) VALUES ('proxy_url', ?)", (proxy_url,)) conn.commit() conn.close() subprocess.run("systemctl restart freellmapi", shell=True, capture_output=True, timeout=15) return True except: return False
def get_mihomo_status(): r = run_cmd(f"systemctl is-active {MIHOMO_SERVICE}") active = r["ok"] and r["msg"] == "active" pid_r = run_cmd(f"systemctl show -p MainPID --value {MIHOMO_SERVICE}") pid = pid_r.get("msg", "0").strip() return {"active": active, "pid": pid}
class Handler(http.server.BaseHTTPRequestHandler): def check_auth(self): if self.headers.get("Authorization", "") != AUTH: self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.end_headers() self.wfile.write(b"<html><body><h1>403</h1></body></html>") return False return True
def do_GET(self): if self.path in ["/", "/index.html"]: self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.end_headers() self.wfile.write(HTML.encode("utf-8")) elif self.path == "/api/status": self.json_response(get_mihomo_status()) elif self.path == "/api/config": try: with open(CONFIG_PATH, "r") as f: self.json_response({"ok": True, "content": f.read()}) except Exception as e: self.json_response({"ok": False, "msg": str(e)}) elif self.path == "/api/log": r = run_cmd(f"journalctl -u {MIHOMO_SERVICE} --no-pager -n 30 --output=cat") self.json_response({"ok": r["ok"], "content": r["msg"]}) else: self.send_response(404) self.end_headers()
def do_POST(self): length = int(self.headers.get("Content-Length", 0)) body = self.wfile.read(length).decode() if length else "{}"
if self.path == "/api/start": r = run_cmd(f"systemctl start {MIHOMO_SERVICE}") if r["ok"]: set_freellmapi_proxy("http://127.0.0.1:7890") self.json_response({"ok": r["ok"], "msg": "mihomo 已启动,代理已设置" if r["ok"] else r["msg"]}) elif self.path == "/api/stop": r = run_cmd(f"systemctl stop {MIHOMO_SERVICE}") if r["ok"]: set_freellmapi_proxy("") self.json_response({"ok": r["ok"], "msg": "mihomo 已停止,已切换直连" if r["ok"] else r["msg"]}) elif self.path == "/api/restart": r = run_cmd(f"systemctl restart {MIHOMO_SERVICE}") if r["ok"]: set_freellmapi_proxy("http://127.0.0.1:7890") self.json_response({"ok": r["ok"], "msg": "mihomo 已重启,代理已恢复" if r["ok"] else r["msg"]}) elif self.path == "/api/reboot": run_cmd("nohup sh -c 'sleep 2 && reboot' >/dev/null 2>&1 &") self.json_response({"ok": True, "msg": "服务器正在重启..."}) elif self.path == "/api/config": try: data = json.loads(body) with open(CONFIG_PATH, "w") as f: f.write(data.get("content", "")) r = run_cmd(f"systemctl restart {MIHOMO_SERVICE}") self.json_response({"ok": r["ok"], "msg": "配置已保存并重启" if r["ok"] else r["msg"]}) except Exception as e: self.json_response({"ok": False, "msg": str(e)}) else: self.send_response(404) self.end_headers()
def json_response(self, data): self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(json.dumps(data).encode())
def log_message(self, *args): pass
class ReusableTCPServer(socketserver.TCPServer): allow_reuse_address = True
if __name__ == "__main__": port = int(sys.argv[1]) if len(sys.argv) > 1 else PORT with ReusableTCPServer(("0.0.0.0", port), Handler) as httpd: print(f"Panel on :{port}", flush=True) try: httpd.serve_forever() except KeyboardInterrupt: pass PYEOF
|