#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Добавляет на VPS отдельный ключ для шлюза в доме. ЗАЧЕМ ОТДЕЛЬНЫЙ КЛЮЧ. Шлюз — это устройство, а не человек. Ему нужен свой ключ, чтобы: * видеть в статистике, что это шлюз, а не чья-то подмена; * отозвать доступ шлюзу, не задев людей; * при поломке шлюза менять только его ключ. Ключ добавляется во ВСЕ входы (TLS, XHTTP, Reality) — чтобы шлюз мог пользоваться любым каналом и переключаться между ними сам. Hysteria2 авторизуется паролем, не ключом, поэтому там ничего не нужно. Осторожность: копия, проверка конфигурации до применения, откат, проверка живым подключением после. """ import json import os import shutil import subprocess import sys import time import uuid VPS = "193.233.210.184" CFG = "/usr/local/etc/xray/config.json" EMAIL = "gateway-home@buryans.local" def sh(cmd, timeout=60): return subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) print("=== 1. ЧИТАЮ КОНФИГУРАЦИЮ VPS ===") r = sh("ssh -o BatchMode=yes root@%s cat %s" % (VPS, CFG)) if not r.stdout.strip(): sys.exit("не получил конфигурацию: %s" % r.stderr[:200]) cfg = json.loads(r.stdout) print(" входящих: %d" % len(cfg["inbounds"])) # если ключ шлюза уже есть — не дублирую existing = None for ib in cfg["inbounds"]: for c in ib.get("settings", {}).get("clients", []): if c.get("email") == EMAIL: existing = c["id"] break if existing: break if existing: print(" ключ шлюза уже есть: %s..." % existing[:8]) new_id = existing else: new_id = str(uuid.uuid4()) print(" новый ключ: %s..." % new_id[:8]) print() print("=== 2. КОПИЯ ===") stamp = time.strftime("%Y%m%d_%H%M%S") bak = "%s.before-gateway-key-%s" % (CFG, stamp) r = sh("ssh -o BatchMode=yes root@%s 'cp -p %s %s && echo ок'" % (VPS, CFG, bak)) print(" %s" % (r.stdout.strip() or r.stderr.strip()[:100])) print() print("=== 3. ДОБАВЛЯЮ КЛЮЧ ВО ВСЕ ВХОДЫ VLESS ===") added = 0 for ib in cfg["inbounds"]: if ib.get("protocol") != "vless": continue clients = ib.setdefault("settings", {}).setdefault("clients", []) if any(c.get("email") == EMAIL for c in clients): print(" порт %-5s уже есть" % ib.get("port")) continue clients.append({"id": new_id, "email": EMAIL}) added += 1 print(" порт %-5s добавлен (всего %d)" % (ib.get("port"), len(clients))) if added == 0: print(" добавлять нечего") print() print("=== 4. ОТПРАВЛЯЮ НА VPS И ПРОВЕРЯЮ ДО ПРИМЕНЕНИЯ ===") payload = json.dumps(cfg, indent=2, ensure_ascii=False) local = "/tmp/vps-cfg-new.json" with open(local, "w", encoding="utf-8") as f: f.write(payload) sh("scp -q -o BatchMode=yes %s root@%s:/tmp/vps-cfg-new.json" % (local, VPS)) r = sh("ssh -o BatchMode=yes root@%s 'xray run -test -config /tmp/vps-cfg-new.json 2>&1 | tail -2'" % VPS) print(" %s" % r.stdout.strip().replace("\n", "\n ")) if "Configuration OK" not in r.stdout: print(" ОШИБКА проверки — не применяю") sh("ssh -o BatchMode=yes root@%s 'rm -f /tmp/vps-cfg-new.json'" % VPS) sys.exit(1) print() print("=== 5. ПРИМЕНЯЮ ===") r = sh("ssh -o BatchMode=yes root@%s 'cp /tmp/vps-cfg-new.json %s && " "systemctl restart xray && sleep 3 && systemctl is-active xray && " "rm -f /tmp/vps-cfg-new.json'" % (VPS, CFG)) print(" служба: %s" % r.stdout.strip()) print() print("=== 6. ПРОВЕРЯЮ ЖИВЫМ ПОДКЛЮЧЕНИЕМ ЭТИМ КЛЮЧОМ ===") client = { "log": {"loglevel": "warning"}, "inbounds": [{"listen": "127.0.0.1", "port": 10890, "protocol": "socks", "settings": {"udp": True, "auth": "noauth"}}], "outbounds": [{"protocol": "vless", "settings": {"vnext": [{"address": VPS, "port": 10443, "users": [{"id": new_id, "encryption": "none"}]}]}, "streamSettings": {"network": "tcp", "security": "tls", "tlsSettings": { "serverName": "git.buryans.ru", "fingerprint": "firefox", "allowInsecure": False}}}], } cp = "/tmp/gw-key-test.json" json.dump(client, open(cp, "w", encoding="utf-8"), indent=2) proc = subprocess.Popen(["xray", "run", "-config", cp], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(5) ip = sh("curl -s --max-time 20 --socks5-hostname 127.0.0.1:10890 " "https://api.ipify.org").stdout.strip() proc.terminate() try: proc.wait(timeout=5) except Exception: proc.kill() print(" выходной адрес ключом шлюза: %s" % (ip or "нет ответа")) print() if ip == VPS: with open("/root/.buryan-gateway-key", "w", encoding="utf-8") as f: f.write("UUID=%s\nEMAIL=%s\n" % (new_id, EMAIL)) os.chmod("/root/.buryan-gateway-key", 0o600) print("=" * 60) print(" КЛЮЧ ШЛЮЗА РАБОТАЕТ") print(" uuid: %s..." % new_id[:8]) print(" данные: /root/.buryan-gateway-key") print("=" * 60) else: print(" КЛЮЧ НЕ РАБОТАЕТ — ОТКАТ") sh("ssh -o BatchMode=yes root@%s 'cp -p %s %s && systemctl restart xray'" % (VPS, bak, CFG)) sys.exit(1)