#!/usr/bin/env python3 """ check_configs.py - تست کانفیگ‌های پراکسی برای دسترسی به api.anthropic.com نیازمندی‌ها: - Python 3.9+ (بدون پکیج اضافه) - sing-box.exe کنار همین فایل (یا در PATH) استفاده: python check_configs.py configs.txt python check_configs.py configs.txt --workers 8 --timeout 12 ورودی: فایل متنی، هر خط یک لینک (vless:// vmess:// trojan:// ss://) یا یک اشتراک base64 کامل. خروجی: working.txt (کانفیگ‌های سالم، مرتب‌شده بر اساس سرعت) و report.csv """ import argparse import base64 import csv import json import os import shutil import socket import subprocess import sys import tempfile import time import urllib.error import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed TEST_URL = "https://api.anthropic.com/v1/models" # بدون API key جواب 401 می‌دهد = یعنی TLS و مسیر سالم است OK_CODES = {200, 401, 404, 405} BASE_PORT = 21000 SCHEMES = ("vless://", "vmess://", "trojan://", "ss://") # ---------- parsing ---------- def b64d(s: str) -> str: s = s.strip().replace("-", "+").replace("_", "/") s += "=" * (-len(s) % 4) return base64.b64decode(s).decode("utf-8", "ignore") def q(p, key, default=""): return p.get(key, [default])[0] def tls_block(p, default_sni, force=False): sec = q(p, "security") if force and not sec: sec = "tls" if sec not in ("tls", "reality"): return None t = { "enabled": True, "server_name": q(p, "sni") or q(p, "host") or default_sni, "insecure": q(p, "allowInsecure") in ("1", "true"), "utls": {"enabled": True, "fingerprint": q(p, "fp") or "chrome"}, } if q(p, "alpn"): t["alpn"] = [a for a in urllib.parse.unquote(q(p, "alpn")).split(",") if a] if sec == "reality": t["reality"] = {"enabled": True, "public_key": q(p, "pbk"), "short_id": q(p, "sid")} return t def transport_block(typ, path, host, service): if typ == "ws": t = {"type": "ws", "path": path or "/"} if "ed=" in t["path"]: base, _, qs = t["path"].partition("?") ed = urllib.parse.parse_qs(qs).get("ed", [""])[0] if ed.isdigit(): t["path"] = base t["max_early_data"] = int(ed) t["early_data_header_name"] = "Sec-WebSocket-Protocol" if host: t["headers"] = {"Host": host} return t if typ == "grpc": return {"type": "grpc", "service_name": service or path} if typ in ("h2", "http"): return {"type": "http", "path": path or "/", "host": [host] if host else []} if typ == "httpupgrade": return {"type": "httpupgrade", "path": path or "/", "host": host} return None def parse_vless(link): u = urllib.parse.urlsplit(link) p = urllib.parse.parse_qs(u.query) o = {"type": "vless", "server": u.hostname, "server_port": u.port, "uuid": urllib.parse.unquote(u.username or "")} if q(p, "flow"): o["flow"] = q(p, "flow") tls = tls_block(p, u.hostname) if tls: o["tls"] = tls tr = transport_block(q(p, "type", "tcp"), urllib.parse.unquote(q(p, "path")), q(p, "host"), q(p, "serviceName")) if tr: o["transport"] = tr return o def parse_trojan(link): u = urllib.parse.urlsplit(link) p = urllib.parse.parse_qs(u.query) o = {"type": "trojan", "server": u.hostname, "server_port": u.port, "password": urllib.parse.unquote(u.username or "")} tls = tls_block(p, u.hostname, force=True) if tls: o["tls"] = tls tr = transport_block(q(p, "type", "tcp"), urllib.parse.unquote(q(p, "path")), q(p, "host"), q(p, "serviceName")) if tr: o["transport"] = tr return o def parse_vmess(link): d = json.loads(b64d(link[len("vmess://"):].split("#")[0])) o = {"type": "vmess", "server": d["add"], "server_port": int(d["port"]), "uuid": d["id"], "security": d.get("scy") or "auto", "alter_id": int(d.get("aid") or 0)} p = {"security": [("tls" if d.get("tls") == "tls" else "")], "sni": [d.get("sni", "")], "alpn": [d.get("alpn", "")], "fp": [d.get("fp", "")]} tls = tls_block(p, d.get("host") or d["add"]) if tls: o["tls"] = tls tr = transport_block(d.get("net", "tcp"), d.get("path", ""), d.get("host", ""), d.get("path", "")) if tr: o["transport"] = tr return o def parse_ss(link): rest = link[len("ss://"):].split("#")[0] rest = rest.split("?")[0] if "plugin=" not in rest else None if rest is None: raise ValueError("ss plugin not supported") if "@" in rest: userinfo, hostport = rest.rsplit("@", 1) if ":" not in userinfo: userinfo = b64d(userinfo) userinfo = urllib.parse.unquote(userinfo) else: decoded = b64d(rest) userinfo, hostport = decoded.rsplit("@", 1) method, password = userinfo.split(":", 1) host, port = hostport.rsplit(":", 1) return {"type": "shadowsocks", "server": host.strip("[]"), "server_port": int(port), "method": method, "password": password} def to_outbound(link): o = {"vless://": parse_vless, "vmess://": parse_vmess, "trojan://": parse_trojan, "ss://": parse_ss}[ next(s for s in SCHEMES if link.startswith(s))](link) o["tag"] = "proxy" return o def load_links(path): text = open(path, encoding="utf-8", errors="ignore").read().strip() if "://" not in text.splitlines()[0]: try: text = b64d(text) except Exception: pass seen, links = set(), [] for line in text.splitlines(): line = line.strip() if line.startswith(SCHEMES) and line not in seen: seen.add(line) links.append(line) return links # ---------- testing ---------- def wait_port(port, proc, tries=40): for _ in range(tries): if proc.poll() is not None: return False try: with socket.create_connection(("127.0.0.1", port), timeout=0.3): return True except OSError: time.sleep(0.15) return False def test_one(idx, link, singbox, timeout): res = {"index": idx, "link": link, "status": "fail", "latency_ms": "", "detail": ""} try: outbound = to_outbound(link) except Exception as e: res["detail"] = f"parse error: {e}" return res port = BASE_PORT + idx cfg = { "log": {"level": "error"}, "inbounds": [{"type": "mixed", "listen": "127.0.0.1", "listen_port": port}], "outbounds": [outbound, {"type": "direct", "tag": "direct"}], } tmp = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") json.dump(cfg, tmp) tmp.close() flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0 proc = subprocess.Popen([singbox, "run", "-c", tmp.name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=flags) try: if not wait_port(port, proc): res["detail"] = "sing-box did not start (invalid config?)" return res proxy = f"http://127.0.0.1:{port}" opener = urllib.request.build_opener( urllib.request.ProxyHandler({"http": proxy, "https": proxy})) req = urllib.request.Request(TEST_URL, headers={"User-Agent": "curl/8.0"}) t0 = time.time() try: r = opener.open(req, timeout=timeout) code = r.status except urllib.error.HTTPError as e: code = e.code ms = int((time.time() - t0) * 1000) res["latency_ms"] = ms if code in OK_CODES: res["status"] = "ok" elif code == 403: res["status"] = "blocked" res["detail"] = "HTTP 403 (exit IP/region blocked)" else: res["detail"] = f"HTTP {code}" except Exception as e: res["detail"] = str(getattr(e, "reason", e))[:120] finally: proc.kill() try: os.unlink(tmp.name) except OSError: pass return res def main(): ap = argparse.ArgumentParser() ap.add_argument("file") ap.add_argument("--workers", type=int, default=8) ap.add_argument("--timeout", type=int, default=12) ap.add_argument("--singbox", default=None) a = ap.parse_args() singbox = a.singbox or shutil.which("sing-box") or ( "./sing-box.exe" if os.path.exists("sing-box.exe") else None) if not singbox: sys.exit("sing-box پیدا نشد. sing-box.exe را کنار این فایل بگذارید.") links = load_links(a.file) print(f"{len(links)} config loaded. testing against {TEST_URL}\n") results = [] with ThreadPoolExecutor(max_workers=a.workers) as ex: futs = [ex.submit(test_one, i, l, singbox, a.timeout) for i, l in enumerate(links)] for n, f in enumerate(as_completed(futs), 1): r = f.result() results.append(r) mark = {"ok": "OK ", "blocked": "BLOCKED", "fail": "FAIL "}[r["status"]] print(f"[{n}/{len(links)}] {mark} {r['latency_ms']!s:>6} ms {r['detail']}") good = sorted((r for r in results if r["status"] == "ok"), key=lambda r: r["latency_ms"]) with open("working.txt", "w", encoding="utf-8") as f: f.write("\n".join(r["link"] for r in good)) with open("report.csv", "w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=["index", "status", "latency_ms", "detail", "link"]) w.writeheader() for r in sorted(results, key=lambda r: r["index"]): w.writerow({k: r[k] for k in w.fieldnames}) print(f"\nدرست: {len(good)} | بلاک‌شده توسط Anthropic: " f"{sum(r['status']=='blocked' for r in results)} | ناموفق: " f"{sum(r['status']=='fail' for r in results)}") print("خروجی: working.txt , report.csv") if __name__ == "__main__": main()