import asyncio
import json
import random
import re

import aiohttp

LINE = re.compile(r"^open tcp (\d+) (\S+) ")
API = {"jsonrpc": "2.0", "method": "apiinfo.version", "params": {}, "id": 1}


def load(n):
    """Pick n lines spread across the whole list, not just the head."""
    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(7)
    return random.sample(rows, min(n, len(rows))), len(rows)


async def api_version(sess, url):
    try:
        async with sess.post(url, json=API, ssl=False, allow_redirects=False) as r:
            if r.status != 200:
                return None
            raw = await r.content.read(600)
        v = json.loads(raw).get("result")
        return v if isinstance(v, str) and v[:1].isdigit() else None
    except Exception:
        return None


async def one(sess, sem, port, ip, out, stat):
    scheme = "https" if port == 443 else "http"
    base = "%s://%s:%d" % (scheme, ip, port)
    try:
        async with sem:
            v1, v2 = await asyncio.gather(api_version(sess, base + "/api_jsonrpc.php"),
                                          api_version(sess, base + "/zabbix/api_jsonrpc.php"))
            if v1 or v2:
                out.append("%s:%d path=%s ver=%s" % (ip, port, "/" if v1 else "/zabbix/", v1 or v2))
            stat["n"] += 1
    except Exception as e:
        stat[type(e).__name__] += 1


async def main():
    rows, total = load(10000)
    out, stat = [], {"n": 0}
    sem = asyncio.Semaphore(2500)
    to = aiohttp.ClientTimeout(total=5, connect=3, sock_read=4)
    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, out, stat) for p, ip in rows])
    dt = asyncio.get_event_loop().time() - t0
    print("list size=%d sample=%d checked=%d in %.0fs" % (total, len(rows), stat["n"], dt))
    print("zabbix api hits=%d" % len(out))
    for x in out[:40]:
        print("  ", x)


asyncio.run(main())
