#!/usr/bin/env python3
"""TCP 连通性测试，可经 SOCKS5 代理；打印是否连上 + 首包 banner"""
import socket, struct, sys, time, json, urllib.request

PX_HOST, PX_PORT = "127.0.0.1", 7897

def socks_connect(host, port, timeout=8):
    s = socket.create_connection((PX_HOST, PX_PORT), timeout=timeout)
    s.settimeout(timeout)
    s.sendall(b"\x05\x01\x00")
    if s.recv(2) != b"\x05\x00":
        raise RuntimeError("socks 握手失败")
    if host.replace(".", "").isdigit():
        req = b"\x05\x01\x00\x01" + socket.inet_aton(host)
    else:
        b = host.encode()
        req = b"\x05\x01\x00\x03" + bytes([len(b)]) + b
    s.sendall(req + struct.pack("!H", port))
    rep = s.recv(10)
    if len(rep) < 2:
        raise RuntimeError("代理无响应")
    code = rep[1]
    if code != 0:
        errs = {1:"一般失败",2:"规则禁止",3:"网络不可达",4:"主机不可达",5:"连接被拒绝",6:"TTL 超时",7:"命令不支持",8:"地址类型不支持"}
        raise RuntimeError("代理返回 %d (%s)" % (code, errs.get(code, "?")))
    return s

def probe(host, port, banner_ms=2500):
    t0 = time.time()
    try:
        s = socks_connect(host, port)
    except Exception as e:
        return "FAIL %.2fs  %s" % (time.time()-t0, e)
    dt = (time.time()-t0)*1000
    s.settimeout(banner_ms/1000)
    data = b""
    try:
        data = s.recv(120)
    except socket.timeout:
        pass
    except Exception as e:
        return "OPEN %.0fms  读错误:%s" % (dt, e)
    try: s.close()
    except: pass
    txt = data.decode("utf-8", "replace").strip().replace("\r", " ").replace("\n", " ")
    return ("OPEN %.0fms  banner=%r" % (dt, txt[:80])) if txt else ("OPEN %.0fms  (无 banner，端口开但服务不说话)" % dt)

def set_group(name):
    url = "http://127.0.0.1:9099/proxies/" + urllib.parse.quote("🎯 最终出口")
    req = urllib.request.Request(url, data=json.dumps({"name": name}).encode(), method="PUT")
    urllib.request.urlopen(req, timeout=5).read()

import urllib.parse

if __name__ == "__main__":
    group = sys.argv[1]
    targets = [tuple(x.split(":")) for x in sys.argv[2:]]
    set_group(group)
    time.sleep(0.8)
    print("### 出口组: %s" % group)
    for h, p in targets:
        print("  %-22s %s" % (h + ":" + p, probe(h, int(p))))
