Created
March 9, 2020 09:28
-
-
Save tonybaloney/4a64c6df62aa3b07417a156d0a386468 to your computer and use it in GitHub Desktop.
TCP Scanner with async generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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