• XSS.stack #1 – первый литературный журнал от юзеров форума

Port scanning python script

blacky

RAID-массив
Пользователь
Регистрация
17.07.2023
Сообщения
69
Реакции
22
Python:
import socket
import argparse
from datetime import datetime

# Function to perform the port scan
def port_scanner(target, start_port, end_port):
    print(f"[*] Starting scan on target: {target}")
    
    # Start time of the scan
    start_time = datetime.now()
    
    # Try to resolve the target hostname to an IP address
    try:
        target_ip = socket.gethostbyname(target)
    except socket.gaierror:
        print(f"[-] Could not resolve hostname: {target}")
        return

    print(f"[*] IP Address of Target: {target_ip}")
    print(f"[*] Scanning ports from {start_port} to {end_port}...")

    # Scanning ports within the specified range
    for port in range(start_port, end_port + 1):
        # Create a new socket for each connection attempt
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)  # 1 second timeout for connections

        result = sock.connect_ex((target_ip, port))  # Try to connect
        if result == 0:
            print(f"[+] Port {port} is open")
        sock.close()

    # Calculate total scan time
    end_time = datetime.now()
    total_time = end_time - start_time
    print(f"[*] Scan completed in {total_time}")

# Main function to handle command-line arguments
if __name__ == "__main__":
    # Create the parser for command-line arguments
    parser = argparse.ArgumentParser(description="Simple Python Port Scanner")
    parser.add_argument("target", help="Target IP or hostname to scan")
    parser.add_argument("--start_port", type=int, default=1, help="Start port for scanning (default: 1)")
    parser.add_argument("--end_port", type=int, default=65535, help="End port for scanning (default: 65535)")

    # Parse the arguments from the command line
    args = parser.parse_args()

    # Call the port scanner function with the parsed arguments
    port_scanner(args.target, args.start_port, args.end_port)


Running the Script:
Save the script as port_scanner.py and run it from the command line:

Код:
python3 port_scanner.py <target> --start_port <start_port> --end_port <end_port>

For example, to scan a host 192.168.1.1 for open ports between 1 and 1000, use:
Код:
python3 port_scanner.py 192.168.1.1 --start_port 1 --end_port 1000

Key Points:
Target: The IP or hostname of the machine you are scanning.
Ports: You can define a port range, e.g., from port 1 to 65535 (default if no range is specified).
Dependencies:
This script uses only the built-in Python libraries (socket, argparse, and datetime), so there are no external dependencies.
 
The above quote has been enhanced with three other features:
  • multi-threading
  • logging and
  • banner grabbing capabilities
Python:
import socket
import argparse
from datetime import datetime
import threading
import queue

# Define a queue for ports to scan in parallel
port_queue = queue.Queue()

# Lock for thread-safe printing
print_lock = threading.Lock()

# Function to grab the banner of the service running on the port
def grab_banner(sock):
    try:
        sock.send(b"HEAD / HTTP/1.1\r\n\r\n")
        banner = sock.recv(1024).decode().strip()
        return banner
    except:
        return None

# Function to scan a single port
def scan_port(target_ip, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.setdefaulttimeout(1)  # Timeout set to 1 second
    result = sock.connect_ex((target_ip, port))
    if result == 0:
        banner = grab_banner(sock)
        with print_lock:
            if banner:
                print(f"[+] Port {port} is open: {banner}")
            else:
                print(f"[+] Port {port} is open, but no banner retrieved.")
    sock.close()

# Worker function for multi-threaded scanning
def worker(target_ip):
    while not port_queue.empty():
        port = port_queue.get()
        scan_port(target_ip, port)
        port_queue.task_done()

# Main function for scanning the ports
def port_scanner(target, start_port, end_port, thread_count):
    print(f"[*] Starting scan on target: {target}")
    
    # Start time of the scan
    start_time = datetime.now()

    # Resolve the target hostname to an IP address
    try:
        target_ip = socket.gethostbyname(target)
    except socket.gaierror:
        print(f"[-] Could not resolve hostname: {target}")
        return

    print(f"[*] IP Address of Target: {target_ip}")
    print(f"[*] Scanning ports from {start_port} to {end_port}...")

    # Fill the queue with the port range
    for port in range(start_port, end_port + 1):
        port_queue.put(port)

    # Start threads for scanning
    threads = []
    for _ in range(thread_count):
        t = threading.Thread(target=worker, args=(target_ip,))
        threads.append(t)
        t.start()

    # Wait for all threads to finish
    port_queue.join()

    # Calculate the total scan time
    end_time = datetime.now()
    total_time = end_time - start_time
    print(f"[*] Scan completed in {total_time}")

# Main function to handle command-line arguments
if __name__ == "__main__":
    # Create the parser for command-line arguments
    parser = argparse.ArgumentParser(description="Enhanced Python Port Scanner with Banner Grabbing")
    parser.add_argument("target", help="Target IP or hostname to scan")
    parser.add_argument("--start_port", type=int, default=1, help="Start port for scanning (default: 1)")
    parser.add_argument("--end_port", type=int, default=65535, help="End port for scanning (default: 65535)")
    parser.add_argument("--threads", type=int, default=10, help="Number of threads to use (default: 10)")

    # Parse the arguments from the command line
    args = parser.parse_args()

    # Call the port scanner function with the parsed arguments
    port_scanner(args.target, args.start_port, args.end_port, args.threads)

Running the Script:
Save the script as enhanced_port_scanner.py and run it from the command line:
Код:
python3 enhanced_port_scanner.py <target> --start_port <start_port> --end_port <end_port> --threads <number_of_threads>

For example, to scan ports from 1 to 1000 on the target 192.168.1.1 with 20 threads, use:
Код:
python3 enhanced_port_scanner.py 192.168.1.1 --start_port 1 --end_port 1000 --threads 20

Dependencies:
No external dependencies are required. This script only uses Python’s built-in libraries (socket, argparse, threading, and queue).
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх