Files
buryan-infra/ops/vpn/reality/reality-probe-test.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

145 lines
5.9 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ОКОНЧАТЕЛЬНАЯ проверка Reality: без bash, без зарезервированных имён.
СЧЁТ ОШИБОК В ЭТОМ РАЗБОРЕ (все мои, не поломки):
1. подставлял заглушку вместо публичного ключа;
2. брал ключ, которого нет на Reality-входе (там были другие);
3. пробовал сайт www.microsoft.com, недоступный с VPS;
4. тестировал на порту, не открытом в экране;
5. проба не запускалась;
6. использовал имя UID, зарезервированное в bash -> ключ пустой.
Сервер прямо и сказал: «invalid request user id».
Теперь проверяю на чистом Python: создаю вход с правильным ключом,
запускаю отвязанно, подключаюсь снаружи.
"""
import json
import subprocess
import time
VPS = "45.133.209.253"
XRAY = "/usr/local/bin/xray"
PORT = 2096
SOCKS = 10903
USER_ID = "11111111-2222-3333-4444-555555555555"
SHORT_ID = "0123456789abcdef"
SNI = "git.buryans.ru"
DEST = "127.0.0.1:10443"
def sh(cmd, timeout=90):
return subprocess.run(cmd, shell=True, capture_output=True,
text=True, timeout=timeout)
def sh_in(cmd, text, timeout=90):
return subprocess.run(cmd, shell=True, input=text, capture_output=True,
text=True, timeout=timeout)
out = sh("%s x25519" % XRAY).stdout
priv = [l.split(":", 1)[1].strip() for l in out.splitlines()
if l.startswith("PrivateKey")][0]
pub = [l.split(":", 1)[1].strip() for l in out.splitlines()
if l.startswith("Password")][0]
server = {
"log": {"loglevel": "debug"},
"inbounds": [{
"listen": "0.0.0.0", "port": PORT, "protocol": "vless",
"settings": {"clients": [{"id": USER_ID, "email": "probe"}],
"decryption": "none"},
"streamSettings": {"network": "tcp", "security": "reality",
"realitySettings": {
"show": False, "dest": DEST, "xver": 0,
"serverNames": [SNI],
"privateKey": priv, "shortIds": [SHORT_ID]}}}],
"outbounds": [{"protocol": "freedom"}],
}
print("=== 1. КЛАДУ КОНФИГ НА VPS ===")
local = "/tmp/probe-srv.json"
with open(local, "w", encoding="utf-8") as f:
json.dump(server, f, indent=2, ensure_ascii=False)
r = sh("scp -q -o BatchMode=yes %s root@%s:/tmp/probe-srv.json" % (local, VPS))
print(" скопирован" if r.returncode == 0 else " ОШИБКА: %s" % r.stderr[:100])
print()
print("=== 2. ПРОВЕРЯЮ И ЗАПУСКАЮ ===")
r = sh_in("ssh -o BatchMode=yes root@%s bash -s" % VPS, """
pkill -f probe-srv 2>/dev/null
sleep 1
xray run -test -config /tmp/probe-srv.json 2>&1 | tail -1
setsid nohup xray run -config /tmp/probe-srv.json </dev/null >/tmp/probe2.log 2>&1 &
sleep 3
echo "процессов: $(pgrep -fc probe-srv)"
echo "слушает: $(ss -tln | grep -c ':%d ')"
""" % PORT)
for line in r.stdout.strip().splitlines():
print(" " + line)
print()
print("=== 3. ПРОВЕРЯЮ ПОРТ СНАРУЖИ ===")
r = sh("timeout 5 bash -c 'cat < /dev/null > /dev/tcp/%s/%d' && echo открыт"
% (VPS, PORT))
print(" порт: %s" % (r.stdout.strip() or "НЕ открыт"))
print()
print("=== 4. ПОДКЛЮЧАЮСЬ КАК КЛИЕНТ ===")
client = {
"log": {"loglevel": "debug"},
"inbounds": [{"listen": "127.0.0.1", "port": SOCKS, "protocol": "socks",
"settings": {"udp": True, "auth": "noauth"}}],
"outbounds": [{"protocol": "vless",
"settings": {"vnext": [{"address": VPS, "port": PORT,
"users": [{"id": USER_ID,
"encryption": "none"}]}]},
"streamSettings": {
"network": "tcp", "security": "reality",
"realitySettings": {"serverName": SNI,
"fingerprint": "firefox",
"publicKey": pub,
"shortId": SHORT_ID,
"spiderX": "/"}}}],
}
cp = "/tmp/probe-cli.json"
with open(cp, "w", encoding="utf-8") as f:
json.dump(client, f, indent=2, ensure_ascii=False)
r = sh("%s run -test -config %s" % (XRAY, cp))
print(" клиент: %s" % (r.stdout + r.stderr).strip().splitlines()[-1])
proc = subprocess.Popen([XRAY, "run", "-config", cp],
stdout=open("/tmp/probe-cli.log", "w"),
stderr=subprocess.STDOUT)
time.sleep(5)
direct = sh("curl -s --max-time 15 https://api.ipify.org").stdout.strip()
via = sh("curl -s --max-time 20 --socks5-hostname 127.0.0.1:%d "
"https://api.ipify.org" % SOCKS).stdout.strip()
print(" напрямую: %s" % (direct or "нет ответа"))
print(" через Reality: %s" % (via or "нет ответа"))
print()
print("=== 5. ЧТО СКАЗАЛ СЕРВЕР ===")
r = sh("ssh -o BatchMode=yes root@%s \"grep -iE 'invalid|rejected|accepted|reality' /tmp/probe2.log | tail -8\"" % VPS)
for line in r.stdout.strip().splitlines():
print(" " + line[:150])
proc.terminate()
try:
proc.wait(timeout=5)
except Exception:
proc.kill()
print()
print("=" * 62)
if via == VPS:
print(" REALITY РАБОТАЕТ СНАРУЖИ. Все прежние провалы были ошибками")
print(" проверки, а не поломкой канала.")
else:
print(" Всё ещё не работает: через Reality %r" % via)
print(" Смотри журнал сервера выше — он говорит причину прямо.")
print("=" * 62)