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 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
| #!/usr/bin/env python3 import os import sys import platform import requests import tarfile import subprocess import uuid as uuid_lib import time import signal import threading from pathlib import Path from http.server import HTTPServer, BaseHTTPRequestHandler
def load_env(): env_path = Path(".env") if env_path.exists(): with open(env_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) key = key.strip() value = value.strip().strip(chr(39)+chr(34)) os.environ[key] = value
load_env()
PORT = int(os.environ.get("PORT", "30489"))
NEZHA_SERVER = os.environ.get("NEZHA_SERVER", "") NEZHA_PORT = os.environ.get("NEZHA_PORT", "") NEZHA_KEY = os.environ.get("NEZHA_KEY", "") NEZHA_RUN_DIR = (Path.cwd() / ".tmp").resolve()
SOCKS5_PORT = int(os.environ.get("SOCKS5_PORT", "40000")) EXPOSE_PORT = int(os.environ.get("EXPOSE_PORT", "31000")) RELAY_REMOTE = os.environ.get("RELAY_REMOTE", "fn.gost.gl.edu.eu.org:80") RELAY_PATH = os.environ.get("RELAY_PATH", "")
GITHUB_REPO = "go-gost/gost" GITHUB_API = f"https://api.github.com/repos/{GITHUB_REPO}/releases/latest"
processes = []
def stop_all_processes(signum=None, frame=None): """优雅停止所有子进程""" print("\n🧹 正在停止所有进程...") for p in processes: try: p.terminate() p.wait(timeout=3) except: p.kill() print("✅ 已停止") sys.exit(0)
signal.signal(signal.SIGINT, stop_all_processes)
def get_system_arch(): system = platform.system().lower() machine = platform.machine().lower() if system != "linux": print("❌ 目前仅支持 Linux 系统") sys.exit(1) arch_map = { "x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64", "armv7l": "armv7", "armv6l": "arm64", } arch = arch_map.get(machine, machine) return system, arch
def gost_exists() -> Path | None: cwd = Path.cwd() candidates = [cwd / "gost", cwd / "gost_linux_amd64", cwd / "gost_linux_arm64"] for p in candidates: if p.exists() and p.is_file(): return p for p in cwd.rglob("gost"): if p.is_file(): return p return None
def download_latest_gost(): print("🔍 获取最新 GOST 版本...") resp = requests.get(GITHUB_API, timeout=30) resp.raise_for_status() data = resp.json() version = data["tag_name"] print(f"📦 最新版本: {version}") system, arch = get_system_arch() download_url = None asset_name = None for asset in data["assets"]: name = asset["name"].lower() if "linux" in name and arch in name and name.endswith((".tar.gz", ".tgz")): asset_name = asset["name"] download_url = asset["browser_download_url"] break if not download_url: print(f"❌ 未找到 linux-{arch} 的安装包") sys.exit(1) print(f"⬇️ 正在下载: {asset_name}") r = requests.get(download_url, stream=True, timeout=60) r.raise_for_status() tar_path = Path(asset_name) with open(tar_path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): f.write(chunk) return tar_path, version
def extract_binary(tar_path: Path): print("📦 正在解压...") extract_dir = Path.cwd() with tarfile.open(tar_path, "r:gz") as tar: tar.extractall(path=extract_dir) gost_path = None for member in tar.getmembers(): if member.name.endswith("/gost") or member.name == "gost": gost_path = extract_dir / member.name break if not gost_path or not gost_path.exists(): for p in extract_dir.rglob("gost"): if p.is_file(): gost_path = p break if not gost_path or not gost_path.exists(): print("❌ 无法找到 gost 可执行文件") sys.exit(1) gost_path.chmod(0o755) print(f"✅ gost 已准备就绪: {gost_path}") tar_path.unlink(missing_ok=True) return gost_path
def get_nezha_arch(): machine = platform.machine().lower() if machine in ("x86_64", "amd64"): return "amd64" elif machine in ("aarch64", "arm64"): return "arm64" elif machine == "s390x": return "s390x" else: return machine
def nezha_agent_exists() -> Path | None: bin_path = NEZHA_RUN_DIR / "service" if bin_path.exists() and bin_path.is_file(): return bin_path return None
def download_nezha_agent(): arch = get_nezha_arch() url_map = { "amd64": "https://amd64.sss.hidns.vip/sbsh", "arm64": "https://arm64.sss.hidns.vip/sbsh", "s390x": "https://s390x.sss.hidns.vip/sbsh", } url = url_map.get(arch) if not url: print(f"❌ 不支持的架构: {arch},跳过哪吒Agent下载") return None NEZHA_RUN_DIR.mkdir(parents=True, exist_ok=True) bin_path = NEZHA_RUN_DIR / "service" print(f"⬇️ 正在下载哪吒Agent ({arch})...") try: r = requests.get(url, stream=True, timeout=60) r.raise_for_status() total_size = int(r.headers.get('content-length', 0)) downloaded = 0 last_percent = -1 with open(bin_path, "wb") as f: for chunk in r.iter_content(chunk_size=8192): if chunk: f.write(chunk) downloaded += len(chunk) if total_size > 0: percent = int((downloaded / total_size) * 100) if percent != last_percent and percent % 10 == 0: last_percent = percent mb_dl = downloaded / 1024 / 1024 mb_total = total_size / 1024 / 1024 print(f"📥 下载进度: {percent}% ({mb_dl:.1f}MB / {mb_total:.1f}MB)") bin_path.chmod(0o755) print(f"✅ 哪吒Agent下载完成: {bin_path}") return bin_path except Exception as e: print(f"❌ 哪吒Agent下载失败: {e}") if bin_path.exists(): bin_path.unlink(missing_ok=True) return None
def generate_nezha_config(): NEZHA_RUN_DIR.mkdir(parents=True, exist_ok=True) config_path = NEZHA_RUN_DIR / "config.yaml" if config_path.exists(): print("✅ 哪吒配置文件已存在,跳过生成") return config_path server = NEZHA_SERVER or "nz.gl.edu.eu.org:443" secret = NEZHA_KEY or "" agent_uuid = str(uuid_lib.uuid4()) config_content = f"""server: {server} secret: {secret} uuid: {agent_uuid} debug: false tls: true """ with open(config_path, "w", encoding="utf-8") as f: f.write(config_content) config_path.chmod(0o644) print(f"💾 哪吒配置已保存到: {config_path.absolute()}") return config_path
def start_nezha_agent(): if not NEZHA_SERVER and not NEZHA_KEY: print("⚠️ 未配置 NEZHA_SERVER 和 NEZHA_KEY,跳过哪吒Agent启动") return None config_path = generate_nezha_config() bin_path = nezha_agent_exists() if not bin_path: bin_path = download_nezha_agent() if not bin_path or not bin_path.exists(): print("❌ 哪吒Agent二进制不可用,跳过启动") return None log_path = NEZHA_RUN_DIR / "run.log" cmd = [str(bin_path), "-c", str(config_path)] print(f"🚀 启动哪吒Agent...") print(f" 服务器: {NEZHA_SERVER or 'nz.gl.edu.eu.org:443'}") try: proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) processes.append(proc) print(f"✅ 哪吒Agent已启动 (PID: {proc.pid})") return proc except Exception as e: print(f"❌ 哪吒Agent启动失败: {e}") return None
FAKE_PAGE = """<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TT随笔 | 生活、摄影与日常记录</title> <script src="https://cdn.tailwindcss.com"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css"> <style> .hero-bg { background: linear-gradient(rgba(0,0,0,0.45), rgba(0,0,0,0.65)), url('https://picsum.photos/id/1015/2000/1200') center/cover; } .photo-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; } .photo-card:hover { transform: scale(1.05); } </style> </head> <body class="bg-zinc-50 dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 transition-colors"> <nav class="bg-white/80 dark:bg-zinc-900/80 backdrop-blur-lg border-b border-zinc-200 dark:border-zinc-800 sticky top-0 z-50"> <div class="max-w-6xl mx-auto px-6 py-5 flex justify-between items-center"> <div class="flex items-center gap-3"> <div class="w-9 h-9 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl flex items-center justify-center text-white text-2xl">🌬️</div> <h1 class="text-2xl font-semibold">TT随笔</h1> </div> <div class="hidden md:flex gap-8 text-sm font-medium"> <a href="#" class="hover:text-blue-500 transition">首页</a> <a href="#" class="hover:text-blue-500 transition">文章</a> <a href="#" class="hover:text-blue-500 transition">摄影</a> <a href="#" class="hover:text-blue-500 transition">关于我</a> </div> <button id="theme-toggle" class="w-10 h-10 rounded-2xl hover:bg-zinc-100 dark:hover:bg-zinc-800 flex items-center justify-center"> <i class="fa-solid fa-moon text-xl"></i> </button> </div> </nav> <header class="hero-bg h-[560px] flex items-center text-white"> <div class="max-w-4xl mx-auto px-6 text-center"> <h2 class="text-5xl md:text-6xl font-bold mb-6">把日常过成诗</h2> <p class="text-xl opacity-90">记录生活中的温柔与美好</p> </div> </header> <div class="max-w-6xl mx-auto px-6 py-16"> <section class="mb-20"> <h3 class="text-3xl font-semibold mb-8">最新随笔</h3> <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-8"> <div class="bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow hover:shadow-xl transition"> <img src="https://picsum.photos/id/1015/600/400" class="w-full h-56 object-cover"> <div class="p-6"> <div class="text-xs text-zinc-500 dark:text-zinc-400">2025.05.18 · 生活</div> <h4 class="font-semibold text-xl mt-2 mb-3">雨后清晨的温柔</h4> <p class="text-zinc-600 dark:text-zinc-400 line-clamp-3">昨夜一场大雨,把城市洗得干干净净...</p> </div> </div> <div class="bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow hover:shadow-xl transition"> <img src="https://picsum.photos/id/201/600/400" class="w-full h-56 object-cover"> <div class="p-6"> <div class="text-xs text-zinc-500 dark:text-zinc-400">2025.05.15 · 摄影</div> <h4 class="font-semibold text-xl mt-2 mb-3">城市黄昏的最后一缕光</h4> <p class="text-zinc-600 dark:text-zinc-400 line-clamp-3">在高楼拍下的绝美日落...</p> </div> </div> <div class="bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow hover:shadow-xl transition"> <img src="https://picsum.photos/id/870/600/400" class="w-full h-56 object-cover"> <div class="p-6"> <div class="text-xs text-zinc-500 dark:text-zinc-400">2025.05.12 · 随想</div> <h4 class="font-semibold text-xl mt-2 mb-3">成年人的体面</h4> <p class="text-zinc-600 dark:text-zinc-400 line-clamp-3">学会把情绪藏好,继续向前走...</p> </div> </div> </div> </section> <section> <h3 class="text-3xl font-semibold mb-8">摄影瞬间</h3> <div class="photo-grid"> <div class="photo-card bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow"><img src="https://picsum.photos/id/1015/800/1000" class="w-full"></div> <div class="photo-card bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow"><img src="https://picsum.photos/id/201/800/600" class="w-full"></div> <div class="photo-card bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow"><img src="https://picsum.photos/id/870/800/900" class="w-full"></div> <div class="photo-card bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow"><img src="https://picsum.photos/id/133/800/700" class="w-full"></div> <div class="photo-card bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow"><img src="https://picsum.photos/id/251/800/1100" class="w-full"></div> <div class="photo-card bg-white dark:bg-zinc-900 rounded-3xl overflow-hidden shadow"><img src="https://picsum.photos/id/1016/800/650" class="w-full"></div> </div> </section> </div> <footer class="bg-zinc-900 text-zinc-400 py-12 text-center"> <div class="max-w-6xl mx-auto px-6">© 2025 TT随笔 · 记录生活,感受当下</div> </footer> <script> const toggle = document.getElementById('theme-toggle'); const html = document.documentElement; function setTheme(dark) { if (dark) { html.classList.add('dark'); toggle.innerHTML = '<i class="fa-solid fa-sun text-xl"></i>'; } else { html.classList.remove('dark'); toggle.innerHTML = '<i class="fa-solid fa-moon text-xl"></i>'; } localStorage.setItem('theme', dark ? 'dark' : 'light'); } if (localStorage.getItem('theme') === 'dark' || (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) setTheme(true); toggle.addEventListener('click', () => setTheme(!html.classList.contains('dark'))); </script> </body> </html>"""
class FakePageHandler(BaseHTTPRequestHandler): def log_message(self, format, *args): pass
def do_GET(self): self.send_response(200) self.send_header('Content-Type', 'text/html; charset=utf-8') self.end_headers() self.wfile.write(FAKE_PAGE.encode('utf-8'))
def do_POST(self): self.do_GET()
def start_http_server(): """启动 HTTP 伪装服务器""" try: server = HTTPServer(("0.0.0.0", PORT), FakePageHandler) print(f"🌐 HTTP 伪装页已启动 | 端口: {PORT}")
def serve(): try: server.serve_forever() except: pass
t = threading.Thread(target=serve, daemon=True) t.start() return server except Exception as e: print(f"⚠️ HTTP 伪装页启动失败: {e}") return None
def start_gost(gost_path: Path): """启动 GOST 反向穿透(参考附件代码)""" relay_path = RELAY_PATH if not relay_path: relay_path = "/" + str(uuid_lib.uuid4()) print(f"⚠️ 未配置 RELAY_PATH,自动生成: {relay_path}")
relay_host = RELAY_REMOTE.split(":")[0]
commands = [ [str(gost_path), f"-L=socks5://[::1]:{SOCKS5_PORT}?bind=true"], [ str(gost_path), f"-L=rtcp://:{EXPOSE_PORT}/[::1]:{SOCKS5_PORT}", "-F", f"relay+ws://{RELAY_REMOTE}?path={relay_path}&host={relay_host}" ] ]
print("🚀 启动 GOST 反向穿透模式") print(f" 本地 SOCKS5: [::1]:{SOCKS5_PORT}") print(f" 远程中继: relay+ws://{RELAY_REMOTE}?path={relay_path}&host={relay_host}") print(f" 暴露端口: {EXPOSE_PORT}") print(f" 客户端连接: socks5://{relay_host}:{EXPOSE_PORT}") print()
for cmd in commands: try: proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 ) processes.append(proc) print(f"✅ 已启动: {' '.join(cmd)}") except Exception as e: print(f"❌ 启动失败: {' '.join(cmd)} | 错误: {e}")
def main(): print(f"📁 当前工作目录: {Path.cwd().resolve()}") print(f"📁 哪吒工作目录: {NEZHA_RUN_DIR}") print()
start_nezha_agent()
start_http_server()
existing_gost = gost_exists() if existing_gost: print(f"✅ 发现已存在的 gost: {existing_gost}") print(" 跳过下载,直接启动...") gost_bin = existing_gost else: print("⚠️ 未找到 gost,开始下载最新版本...") tar_path, _ = download_latest_gost() gost_bin = extract_binary(tar_path)
start_gost(gost_bin)
print("\n📡 服务运行中,按 Ctrl+C 停止\n") try: while True: for idx, proc in enumerate(processes): if proc.poll() is None: line = proc.stdout.readline() if line: print(f"[gost-{idx+1}] {line.strip()}") time.sleep(0.1) except KeyboardInterrupt: stop_all_processes()
if __name__ == "__main__": main()
|