import asyncio, re, struct
import aiohttp

ips = [l.split('\t')[0] for l in open('bt_full.tsv') if l.strip()]
SEM = asyncio.Semaphore(20)
OUT = open('bt_versions.tsv', 'w')
LOCK = asyncio.Lock()
HDR = re.compile(rb'^(0 Successful\n.+\n\d+\n)')

def parse(b):
    m = HDR.match(b)
    if not m:
        return None
    d = b[m.end():]
    if b'Thank you for using BeyondTrust' not in d or len(d) < 12:
        return None
    magic, _, _, t1, ln, t2 = struct.unpack('>IBHBBB', d[:10])
    if magic != 0x42524446 or t1 != 0x91 or t2 != 0x81 or not 3 <= ln <= 20:
        return None
    return d[10:10 + ln - 1].decode('ascii', 'replace')

async def one(s, ip):
    try:
        async with SEM:
            async with s.get(f"https://{ip}/get_rdf?comp=sdcust&locale_code=en-us",
                             ssl=False, timeout=aiohttp.ClientTimeout(total=25)) as r:
                b = await r.read() if r.status == 200 else b''
    except Exception:
        b = b''
    v = parse(b) if b else None
    async with LOCK:
        OUT.write("%s\t%s\n" % (ip, v or '-'))
        OUT.flush()

async def main():
    conn = aiohttp.TCPConnector(limit=20, force_close=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        await asyncio.gather(*[one(s, ip) for ip in ips])
    OUT.close()

asyncio.run(main())
