import asyncio, random, re, collections
import aiohttp

PORTS = [9191, 8040, 8041, 7071, 8880, 10443]
N = 60
TITLE = re.compile(r"(?is)<title[^>]*>\s*(.*?)\s*</title>")

def load():
    d = collections.defaultdict(list)
    with open("/root/recon/scan_specprio.list", errors="replace") as f:
        for line in f:
            p = line.split()
            if len(p) >= 4 and p[0] == "open":
                d[int(p[2])].append(p[3])
    return d

async def probe(sess, ip, port):
    for scheme in ("https", "http"):
        try:
            async with sess.get(f"{scheme}://{ip}:{port}/", allow_redirects=False, ssl=False) as r:
                raw = await r.content.read(8192)
                txt = raw.decode("utf-8", "replace")
                t = TITLE.search(txt)
                title = re.sub(r"\s+", " ", t.group(1)).strip()[:60] if t else ""
                return (scheme, r.status, r.headers.get("Server", "")[:40], title, len(raw))
        except Exception:
            continue
    return None

async def main():
    data = load()
    conn = aiohttp.TCPConnector(limit=0, ssl=False)
    tout = aiohttp.ClientTimeout(total=8, connect=5, sock_read=5)
    hdr = {"User-Agent": "Mozilla/5.0"}
    async with aiohttp.ClientSession(connector=conn, timeout=tout, headers=hdr) as sess:
        for port in PORTS:
            ips = random.sample(data.get(port, []), min(N, len(data.get(port, []))))
            res = await asyncio.gather(*[probe(sess, ip, port) for ip in ips])
            c = collections.Counter()
            got = 0
            for r in res:
                if r:
                    got += 1
                    c[(r[0], r[1], r[2], r[3])] += 1
            print(f"=== port {port}: {len(data.get(port, []))} open, sample {len(ips)}, answered {got}")
            for k, v in c.most_common(6):
                print("  ", v, "x", k)
    print("PROBEDONE")

asyncio.run(main())
