Created
November 21, 2024 22:23
-
-
Save watson0x90/31b8e5d4d76d248ca11f1ab56dc5be98 to your computer and use it in GitHub Desktop.
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 | |
from concurrent.futures import ThreadPoolExecutor | |
import ipaddress | |
import argparse | |
def parse_ports(file_path): | |
""" | |
Parses a file containing port numbers and ranges, expanding ranges into individual ports. | |
""" | |
ports = set() # Use a set to avoid duplicates | |
try: | |
with open(file_path, 'r') as file: | |
for line in file: | |
line = line.strip() | |
if not line or line.startswith("#"): # Skip empty lines and comments | |
continue | |
parts = line.split(',') | |
for part in parts: | |
if '-' in part: # Handle ranges like 3-7 | |
start, end = map(int, part.split('-')) | |
ports.update(range(start, end + 1)) | |
else: # Handle individual ports | |
ports.add(int(part)) | |
except Exception as e: | |
print(f"Error reading ports from file: {e}") | |
return [] | |
return sorted(ports) | |
def scan_port(ip, port): | |
"""Attempts to connect to a specified port on a specified IP.""" | |
try: | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
s.settimeout(0.5) | |
s.connect((ip, port)) | |
print(f"[+] Open: {ip}:{port}") | |
except (socket.timeout, ConnectionRefusedError): | |
pass | |
def scan_ip(ip, ports): | |
"""Scans a list of ports on a single IP address.""" | |
print(f"Scanning {ip}...") | |
with ThreadPoolExecutor(max_workers=100) as executor: | |
for port in ports: | |
executor.submit(scan_port, ip, port) | |
def main(): | |
parser = argparse.ArgumentParser(description="Simple Python Port Scanner") | |
parser.add_argument("cidr", help="CIDR range to scan, e.g., 192.168.0.1/24") | |
parser.add_argument("port_file", help="Path to a file containing ports or port ranges (e.g., 3-7,22,80)") | |
args = parser.parse_args() | |
# Parse the port file | |
ports = parse_ports(args.port_file) | |
if not ports: | |
print("No valid ports found to scan.") | |
return | |
try: | |
# Generate all IPs in the provided CIDR range | |
network = ipaddress.ip_network(args.cidr, strict=False) | |
except ValueError as e: | |
print(f"Invalid CIDR range: {e}") | |
return | |
# Scan each IP in the range | |
for ip in network.hosts(): | |
scan_ip(str(ip), ports) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment