Created
October 28, 2022 22:09
-
-
Save danypype/6f6f6f6196d3e494afdad573e824a98f to your computer and use it in GitHub Desktop.
Simple python port scanner
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
from multiprocessing import Process | |
import argparse | |
import socket | |
import time | |
import math | |
def is_port_open(ip_address, port, timeout=1): | |
try: | |
socket.create_connection((ip_address, port), timeout).close() | |
return True | |
except ConnectionRefusedError: | |
return False | |
def scan_ip_address(ip_address, start_port, end_port): | |
for port in range(start_port, end_port): | |
if is_port_open(ip_address, port): | |
print(f"port {port} is open!") | |
def scan_host(hostname, start_port, end_port, workers_count): | |
ip_address = socket.gethostbyname(hostname) | |
print(f"scanning hostname {hostname}") | |
print(f"ip address: {ip_address}") | |
step = math.ceil((end_port - start_port + 1) / workers_count) | |
processes = [] | |
for port in range(start_port, end_port + 1, step): | |
fun_args = (ip_address, port, min(port + step - 1, end_port)) | |
process = Process(target=scan_ip_address, args=fun_args) | |
process.start() | |
processes.append(process) | |
for process in processes: | |
process.join() | |
if __name__ == "__main__": | |
arg_parser = argparse.ArgumentParser() | |
arg_parser.add_argument("--hostname", type=str) | |
arg_parser.add_argument("--start-port", type=int, default=1) | |
arg_parser.add_argument("--end-port", type=int, default=65535) | |
arg_parser.add_argument("--workers", type=int) | |
args = arg_parser.parse_args() | |
start_time = time.time() | |
scan_host(args.hostname, args.start_port, args.end_port, args.workers) | |
end_time = time.time() | |
print(f"elapsed time: {round(end_time - start_time)} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment