import asyncio
import json

import aiohttp

API = {"jsonrpc": "2.0", "method": "apiinfo.version", "params": {}, "id": 1}


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 "HTTP%d" % r.status
            raw = await r.content.read(600)
        v = json.loads(raw).get("result")
        return v if isinstance(v, str) else "noresult"
    except Exception as e:
        return "err:%s" % type(e).__name__


async def one(sess, sem, ip):
    try:
        async with sem:
            a, b = await asyncio.gather(api_version(sess, "https://%s/api_jsonrpc.php" % ip),
                                        api_version(sess, "https://%s/zabbix/api_jsonrpc.php" % ip))
            return ip, a, b
    except Exception as e:
        return ip, "err", type(e).__name__


async def main():
    ips = [l.strip() for l in open("/root/recon/ctrl_hosts.txt") if l.strip()]
    sem = asyncio.Semaphore(100)
    to = aiohttp.ClientTimeout(total=10, connect=4, sock_read=8)
    async with aiohttp.ClientSession(timeout=to,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        res = await asyncio.gather(*[one(s, sem, ip) for ip in ips])
    ok = 0
    for ip, a, b in res:
        good = (a[:1].isdigit(), b[:1].isdigit())
        ok += 1 if any(good) else 0
        print("%-16s root=%-8s zbxpath=%-8s" % (ip, a, b))
    print("detected %d/%d" % (ok, len(ips)))


asyncio.run(main())
