import asyncio, re, collections
import aiohttp

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


def load(n):
    out = []
    with open("/root/recon/scan_zabbix.list") as f:
        for line in f:
            m = LINE.match(line)
            if m:
                out.append((int(m.group(1)), m.group(2)))
            if len(out) >= n:
                break
    return out


async def one(sess, sem, port, ip, stats, found):
    scheme = "https" if port == 443 else "http"
    try:
        async with sem:
            async with sess.get("%s://%s:%d/" % (scheme, ip, port), ssl=False) as r:
                body = (await r.content.read(20000)).decode("utf-8", "replace")
                stats[r.status] += 1
                low = body.lower()
                if "zabbix" in low or "zbx" in low:
                    t = re.search(r"<title>([^<]*)", body, re.I)
                    found.append("%s:%d %s %s" % (ip, port, r.status, (t.group(1) if t else "")[:40]))
    except Exception as e:
        stats[type(e).__name__] += 1


async def main():
    ips = load(30000)
    stats = collections.Counter()
    found = []
    sem = asyncio.Semaphore(3000)
    to = aiohttp.ClientTimeout(total=4, connect=2, sock_read=3)
    async with aiohttp.ClientSession(timeout=to,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        await asyncio.gather(*[one(s, sem, p, ip, stats, found) for p, ip in ips])
    print("sample:", len(ips))
    print("stats:", dict(stats.most_common(8)))
    print("zabbix-marker hits:", len(found))
    for x in found[:25]:
        print("  ", x)


asyncio.run(main())
