Created
February 23, 2022 21:47
-
-
Save Auax/6c84d5a216b19ac184c5fa06dac0bbae to your computer and use it in GitHub Desktop.
Scan ports with Python
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 sys | |
import threading | |
import colorama | |
import tqdm | |
open_ports = [] | |
ip = "192.168.1.1" # Type here the IP you want to scan. I will use 192.168.1.1 as an example | |
def portscan(target: str, port: int) -> None: | |
""" | |
Connect to a given IP using a port | |
:param target: IP target | |
:param port: the port we're going to use to connect | |
:return: None | |
""" | |
# Update variable outside function | |
global open_ports | |
try: | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Initialize socket instance | |
s.settimeout(0.5) # Timeout time before skipping | |
con = s.connect_ex((target, port)) # Connect to target | |
if con == 0: | |
open_ports.append(str(port)) # Append port to the global open_ports variable | |
s.close() | |
except Exception: | |
# If there's an error, ignore it. It means the connection couldn't be possible. | |
pass | |
# Check if the IP is valid | |
assert ip, "IP cannot be blank" | |
try: | |
ip = socket.gethostbyname(ip) | |
except socket.gaierror: | |
print(f"Error in target '{ip}'. Target format must be: 'example.com' or '192.168.1.1'") | |
sys.exit(-1) # Abort execution | |
# Scan ports | |
for i in tqdm.tqdm(range(1, 65535), bar_format="{l_bar}{bar:10}{r_bar}{bar:-10}"): | |
thread = threading.Thread(target=portscan, args=(ip, i)) | |
thread.start() | |
if not open_ports: | |
print("No ports open!") | |
else: | |
for port in open_ports: | |
print(f"Port {colorama.Fore.LIGHTMAGENTA_EX}{port}{colorama.Fore.RESET}:\tOpen") # Print ports |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment