Python: port scanner

 import sys

import socket

import time


def scan_ports(ip, port_range):

    start_port, end_port = map(int, port_range.split('-'))

    total_ports = end_port - start_port + 1

    open_ports = []

    print(f"Scanning IP: {ip}, Port Range: {start_port}-{end_port}")

    print("-" * 50)


    for idx, port in enumerate(range(start_port, end_port + 1), start=1):

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        sock.settimeout(0.5)

        result = sock.connect_ex((ip, port))


        if result == 0:

            try:

                service = socket.getservbyport(port, 'tcp')

            except:

                service = "Unknown Service"

            print(f"Port {port}: Open ({service})")

            open_ports.append((port, service))

        sock.close()


        # Update progress bar

        progress = (idx / total_ports) * 100

        print(f"\rProgress: [{int(progress) * '='}{' ' * (100 - int(progress))}] {progress:.2f}%", end='', flush=True)


    print("\n" + "-" * 50)

    print(f"Scan completed. Found {len(open_ports)} open ports.")


    # Save results to file

    with open("scan_results.txt", "w") as file:

        file.write(f"Scan results for IP: {ip}, Port Range: {start_port}-{end_port}\n")

        file.write("-" * 50 + "\n")

        for port, service in open_ports:

            file.write(f"Port {port}: Open ({service})\n")

        file.write("-" * 50 + "\n")

        file.write(f"Total open ports: {len(open_ports)}\n")


    print("Results saved to scan_results.txt.")


if __name__ == "__main__":

    if len(sys.argv) != 3:

        print("Usage: python3 test.py <IP> <range>")

        print("Example: python3 test.py 192.168.1.1 20-80")

        sys.exit(1)


    target_ip = sys.argv[1]

    port_range = sys.argv[2]


    try:

        start_time = time.time()

        scan_ports(target_ip, port_range)

        end_time = time.time()

        print(f"Scan duration: {end_time - start_time:.2f} seconds.")

    except Exception as e:

        print(f"Error: {e}")