Last active
May 26, 2021 05:15
-
-
Save quasa0/9ca2793e4440300e2f89efcb9bdb31a4 to your computer and use it in GitHub Desktop.
Scan IP for open ports
This file contains hidden or 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 socket | |
import subprocess | |
import sys | |
import asyncio | |
import time | |
from datetime import datetime | |
import concurrent.futures | |
import requests | |
import random | |
def try_port(port): | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.settimeout(5) | |
result = sock.connect_ex((remoteServerIP, port)) | |
sock.settimeout(None) | |
if result == 0: | |
print(f' <<< Port {port} is open >>> ', end='', flush=True) | |
else: | |
r = random.uniform(0, 1) | |
if r < 0.001: | |
print(f' {(datetime.now() - t1).total_seconds()} ', end='', flush=True) | |
if r < 0.01: | |
print('.', end='', flush=True) | |
sock.close() | |
return (port, result) | |
subprocess.call('clear', shell=True) | |
remoteServer = input('Enter ip: ') | |
remoteServerIP = socket.gethostbyname(remoteServer) | |
print('-' * 60 + f'\nPlease wait, scanning remote host {remoteServerIP}\n' + '-' * 60) | |
t1 = datetime.now() | |
async def main(): | |
with concurrent.futures.ThreadPoolExecutor(max_workers=1017) as executor: | |
loop = asyncio.get_event_loop() | |
futures = [ | |
loop.run_in_executor( | |
executor, | |
try_port, | |
i | |
) | |
for i in range(0, 65535) | |
] | |
results = await asyncio.gather(*futures) | |
print('\n\n') | |
for response in results: | |
if response[1] == 0: | |
print(f'Port {response[0]}: \t Open') | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) | |
t2 = datetime.now() | |
print(f'\nTime taken to scan: {(t2 - t1).total_seconds()}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment