import asyncio
import random
import re

import aiohttp

LINE = re.compile(r"^open tcp (\d+) (\S+) ")


def load(n):
    rows = []
    with open("/root/recon/scan_zabbix.list") as f:
        for line in f:
            m = LINE.match(line)
            if m:
                rows.append((int(m.group(1)), m.group(2)))
    random.seed(21)
    return random.sample(rows, min(n, len(rows)))


async def one(sess, sem, port, ip, hits, stat):
    scheme = "https" if port == 443 else "http"
    try:
        async with sem:
            for path in ("/", "/zabbix/"):
                async with sess.head("%s://%s:%d%s" % (scheme, ip, port, path),
                                     ssl=False, allow_redirects=False) as r:
                    stat[r.status] = stat.get(r.status, 0) + 1
                    ck = r.headers.getall("Set-Cookie", [])
                    if any("zbx_session=" in c for c in ck):
                        hits.append("%s:%d%s %d" % (ip, port, path, r.status))
    except Exception as e:
        stat[type(e).__name__] = stat.get(type(e).__name__, 0) + 1


async def main():
    rows = load(20000)
    hits, stat = [], {}
    sem = asyncio.Semaphore(2500)
    to = aiohttp.ClientTimeout(total=4, connect=2, sock_read=3)
    t0 = asyncio.get_event_loop().time()
    async with aiohttp.ClientSession(timeout=to,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        await asyncio.gather(*[one(s, sem, p, ip, hits, stat) for p, ip in rows])
    dt = asyncio.get_event_loop().time() - t0
    print("sample=%d in %.0fs (%.0f/s)" % (len(rows), dt, len(rows) / dt))
    print("statuses:", dict(sorted(stat.items(), key=lambda x: -x[1])[:6]))
    print("zbx_session hits=%d" % len(hits))
    for h in hits[:25]:
        print("  ", h)


asyncio.run(main())
