import asyncio, sys, ipaddress

PORTS = [int(x) for x in sys.argv[1].split(',')]
SUBNETS = sys.argv[2].split(',')
CONC = int(sys.argv[3]) if len(sys.argv) > 3 else 400
OUTF = sys.argv[4] if len(sys.argv) > 4 else '/tmp/.scan.out'
SEM = asyncio.Semaphore(CONC)
OUT = []


async def probe(ip, port):
    async with SEM:
        w = None
        try:
            r, w = await asyncio.wait_for(asyncio.open_connection(ip, port), 3)
            OUT.append((ip, port))
        except Exception:
            pass
        finally:
            if w is not None:
                try:
                    w.close()
                except Exception:
                    pass


async def main():
    tasks = []
    for sn in SUBNETS:
        for ip in ipaddress.ip_network(sn).hosts():
            for p in PORTS:
                tasks.append(asyncio.create_task(probe(str(ip), p)))
    await asyncio.gather(*tasks)
    OUT.sort(key=lambda x: (tuple(int(o) for o in x[0].split('.')), x[1]))
    with open(OUTF, 'w') as f:
        for ip, p in OUT:
            f.write('%s\t%d\n' % (ip, p))
    print('done', len(OUT))

asyncio.run(main())
