#!/usr/bin/env python3
"""挨个机场节点测试能否连到台湾机的 SSH，找出可用的跳板"""
import socket, struct, json, time, urllib.request, urllib.parse, sys

API = "http://127.0.0.1:9099"
TARGET = ("114.41.18.138", 10155)

def api(path, data=None, method="GET"):
    u = API + path
    if data is not None:
        d = json.dumps(data, ensure_ascii=False).encode()
        r = urllib.request.Request(u, data=d, method=method, headers={"Content-Type":"application/json"})
    else:
        r = urllib.request.Request(u, method=method)
    return urllib.request.urlopen(r, timeout=6).read()

def pick(group, name):
    api("/proxies/" + urllib.parse.quote(group),
        {"name": name}, "PUT")

def socks_probe(host, port, wait=5.0):
    try:
        s = socket.create_connection(("127.0.0.1", 7897), 8)
    except Exception as e:
        return "proxy_down"
    s.settimeout(wait)
    try:
        s.sendall(b"\x05\x01\x00")
        if s.recv(2) != b"\x05\x00": return "socks_fail"
        req = b"\x05\x01\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port)
        s.sendall(req)
        rep = s.recv(10)
        if len(rep) < 2 or rep[1] != 0:
            return "dial_fail_%d" % (rep[1] if len(rep) > 1 else -1)
        try:
            d = s.recv(64)
        except socket.timeout:
            return "connect_no_banner"
        return "BANNER:" + d.decode("utf-8","replace").strip().splitlines()[0] if d else "connect_closed"
    finally:
        try: s.close()
        except: pass

nodes = json.loads(api("/proxies/" + urllib.parse.quote("🧪 跳板单点")))["all"]
print("待测节点:", len(nodes), flush=True)
hits = []
for i, n in enumerate(nodes, 1):
    try:
        pick("🧪 跳板单点", n)
        pick("🎯 最终出口", "🧪 跳板单点")
        time.sleep(0.3)
        r = socks_probe(*TARGET)
    except Exception as e:
        r = "err:%s" % e
    mark = "  <<<<<< 命中" if r.startswith("BANNER") else ""
    print(f"[{i:2d}/{len(nodes)}] {n[:40]:42s} {r}{mark}", flush=True)
    if r.startswith("BANNER"):
        hits.append((n, r))
print("\n=== 命中 ===")
for h in hits: print(h)
if not hits: print("(无)")
