Files
buryan-infra/ops/vpn/xhttp/xhttp-test-outer.py
T
architect c985c0617b
lint / hygiene (push) Failing after 30s
lint / hygiene (pull_request) Failing after 21s
standard / check (push) Successful in 9s
standard / check (pull_request) Successful in 14s
[INFRA] migrate active old VPS 193.233.210.184 to 45.133.209.253
2026-12-02 18:00:21 +03:00

127 lines
4.4 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Проверка XHTTP СНАРУЖИ, с домашнего канала.
Главное здесь — не «порт слушает», а что канал действительно пропускает
трафик и выходит через наш VPS. Уже был случай, когда на сервере всё
работало, а снаружи не проходило.
"""
import json
import os
import subprocess
import sys
import time
VPS = "45.133.209.253"
PORT = 8444
PATH = "/buryan-xhttp"
SNI = "git.buryans.ru"
SOCKS = 10811
XRAY = "/usr/local/bin/xray"
# ключ беру с VPS: первый из основного входа
r = subprocess.run(
["ssh", "-o", "BatchMode=yes", "root@%s" % VPS,
"python3 -c \"import json;d=json.load(open('/usr/local/etc/xray/config.json'));"
"print(d['inbounds'][0]['settings']['clients'][0]['id'])\""],
capture_output=True, text=True)
UUID = r.stdout.strip()
if len(UUID) < 30:
sys.exit("не получил ключ: %r" % r.stdout[:120])
print("=== 1. КЛЮЧ ПОЛУЧЕН ===")
print(" первый ключ основного входа, длина %d" % len(UUID))
cfg = {
"log": {"loglevel": "warning"},
"inbounds": [
{"listen": "127.0.0.1", "port": SOCKS, "protocol": "socks",
"settings": {"udp": True, "auth": "noauth"}}
],
"outbounds": [
{"protocol": "vless", "tag": "proxy",
"settings": {"vnext": [{"address": VPS, "port": PORT,
"users": [{"id": UUID, "encryption": "none"}]}]},
"streamSettings": {"network": "xhttp", "security": "tls",
"tlsSettings": {"serverName": SNI, "fingerprint": "firefox",
"allowInsecure": False},
"xhttpSettings": {"host": SNI, "path": PATH, "mode": "auto"}}},
{"protocol": "freedom", "tag": "direct"},
],
}
p = "/tmp/xhttp-client.json"
json.dump(cfg, open(p, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
print()
print("=== 2. ПРОВЕРКА КОНФИГУРАЦИИ КЛИЕНТА ===")
r = subprocess.run([XRAY, "run", "-test", "-config", p],
capture_output=True, text=True)
out = (r.stdout + r.stderr).strip()
print(" %s" % (out.splitlines()[-1] if out else "нет вывода"))
if r.returncode != 0:
print(out[-400:])
sys.exit(1)
print()
print("=== 3. ПОДКЛЮЧАЮСЬ И ПРОВЕРЯЮ КАНАЛ ===")
proc = subprocess.Popen([XRAY, "run", "-config", p],
stdout=open("/tmp/xhttp-client.log", "w"),
stderr=subprocess.STDOUT)
time.sleep(4)
def curl(url, socks=True):
cmd = ["curl", "-s", "--max-time", "25", "-o", "/dev/null",
"-w", "%{http_code}"]
if socks:
cmd += ["--socks5-hostname", "127.0.0.1:%d" % SOCKS]
cmd.append(url)
return subprocess.run(cmd, capture_output=True, text=True).stdout.strip()
def ip_through():
return subprocess.run(
["curl", "-s", "--max-time", "25", "--socks5-hostname",
"127.0.0.1:%d" % SOCKS, "https://api.ipify.org"],
capture_output=True, text=True).stdout.strip()
direct_ip = subprocess.run(
["curl", "-s", "--max-time", "15", "https://api.ipify.org"],
capture_output=True, text=True).stdout.strip()
via_ip = ip_through()
print(" напрямую: %s" % (direct_ip or "нет ответа"))
print(" через XHTTP: %s" % (via_ip or "нет ответа"))
print()
print("=== 4. ЧТО ДОСТУПНО ЧЕРЕЗ XHTTP ===")
for url in ("https://git.buryans.ru/",
"https://matrix.buryans.ru/_matrix/client/versions",
"https://www.youtube.com/"):
print(" %-52s HTTP %s" % (url, curl(url) or "—"))
print()
print("=== 5. ЧТО В ЖУРНАЛЕ КЛИЕНТА ===")
try:
lines = open("/tmp/xhttp-client.log", encoding="utf-8",
errors="replace").read().splitlines()
for line in lines[-6:]:
print(" " + line[:150])
except OSError:
pass
proc.terminate()
try:
proc.wait(timeout=5)
except Exception:
proc.kill()
print()
print("=== ИТОГ ===")
if via_ip == VPS and direct_ip and direct_ip != VPS:
print(" XHTTP РАБОТАЕТ СНАРУЖИ: выходим через %s" % VPS)
print(" (напрямую вышли бы как %s)" % direct_ip)
else:
print(" НЕ ПОДТВЕРДИЛОСЬ: напрямую %r, через XHTTP %r" % (direct_ip, via_ip))