Scanner

import sys
import socket
from datetime import datetime
import threading

def scan_port(target,port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        result = s.connect_ex((target,port)) # error indicator - if 0, port is open
        if result == 0:
            print(f"Port {port} is open")
        s.close()
    except socket.error as e:
        print(f"Socket error on port {port}: {e}")
    except Exception as e:
        print(f"Unexpected error on port {port}: {e}")


# Main function - argument validation and target definition
def main():
    if len(sys.argv) == 2: #  python scanner.py 192.168.1.1
        target = sys.argv[1] # it will get the 192.168.1.1
    else:
        print("Invalid number of arguments.")
        print("Usage: python.exe scanner.py <target>")
        sys.exit(1)

    # Resolve the target hostname to an IP address
    try:
        target_ip = socket.gethostbyname(target)
    except socket.gaierror: # hostname resolution issue
        print(f"Error: Unable to resolve hostname {target}")
        sys.exit(1)

    # Add a pretty banner
    print("-" * 50)
    print(f"Scanning target {target_ip}")
    print(f"Time started: {datetime}")
    print("-" * 50)

    try:
        # Use multithreading to scan ports concurrently
        threads = []
        for ports in range(1,65536):
            thread = threading.Thread(target=scan_port, args=(target_ip, ports))
            threads.append(thread)
            thread.start()
        
        # Wait for all threads to complete
        for thread in threads: # It will pause the main thread while it doesn't completed yet
            thread.join()

    except KeyboardInterrupt:
        print("\nExiting program")
        sys.exit(0) # It will exit cleanly with 0 error code

    except socket.error as e:
        print(f"Socket error: {e}")
        sys.exit(1)

    print("\nScan completed!")

if __name__ == "__main__": # Just making sure that this is not being imported anywhere else
    main() # Not importable 

Last updated