Skip to content

Instantly share code, notes, and snippets.

@tonybaloney
Created March 9, 2020 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonybaloney/4a64c6df62aa3b07417a156d0a386468 to your computer and use it in GitHub Desktop.
Save tonybaloney/4a64c6df62aa3b07417a156d0a386468 to your computer and use it in GitHub Desktop.
TCP Scanner with async generators
import time
import asyncio
timeout = 1.0
async def check_ports(host: str, start: int, end: int, max=10):
found = 0
for port in range(start, end):
try:
future = asyncio.open_connection(host=host, port=port)
r, w = await asyncio.wait_for(future, timeout=timeout)
yield port
found += 1
w.close()
if found >= max:
return
except asyncio.TimeoutError:
pass # closed
async def scan(start, end, host):
results = []
async for port in check_ports(host, start, end, max=1):
results.append(port)
return results
if __name__ == '__main__':
start = time.time()
host = "something-you-own.com"
scan_range = 80, 100
results = asyncio.run(scan(*scan_range, host))
for result in results:
print("Port {0} is open".format(result))
print("Completed scan in {0} seconds".format(time.time() - start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment