Let me Script You: Sniffer Lite v4.0 — Lightweight CLI Diagnostic and Recon Tool for Linux

Author: Perisa Reljic [ ▽ Ш ]

Project: Let me Script You

Environment: Linux / Python 3 (no external Python dependencies)

Introduction

In server administration and website maintenance, the most useful tools are often those that do not require complex installation, heavy libraries, or hours of configuration—running straight from a single file in the terminal and giving a clear picture of the current state right away. That is where Sniffer Lite v4.0 comes from: a lightweight, fast, standalone Python CLI script from the Let me Script You series.

The script is written strictly using the Python 3 standard library (socket, ssl, urllib, subprocess, concurrent.futures, json), meaning it runs out of the box on any modern Linux system (Ubuntu, Debian, BackBox, Mint, Arch, and others), with optional integration for system tools like dig and nmap when present on the machine.

What It Does and What It Is For

Sniffer Lite v4.0 brings several key checks together into a single command-line or interactive menu workflow:

  • Multi-threaded TCP port scanner: Quickly checks the default 17 key service ports, the first 1,000 ports (1k / 1-1000), or any custom port range and list, with lightweight banner grabbing and adjustable thread count (--threads) and timeout (--timeout).
  • TLS/SSL certificate check: Connects to the HTTPS port and reads the protocol version and cipher (e.g., TLSv1.3), certificate issuer, CN, SAN domains, and validity dates.
  • HTTP response and security headers audit: Checks the HTTP status code, final URL after redirects, web server, basic stack detection (e.g., WordPress, WooCommerce, Plesk, Cloudflare), allowed HTTP methods (OPTIONS), cookie flags (HttpOnly, Secure, SameSite), and splits security headers into CORE and OPTIONAL.
  • DNS lookup (--dns): Resolves A (IPv4) and AAAA (IPv6) addresses, and with dig or host also displays NS, MX, and TXT records.
  • Subdomain & Endpoint Recon (--recon): Checks common subdomains (www, mail, webmail, ftp, plesk, cpanel, dev, staging, api, admin, etc.) and key site paths (robots.txt, sitemap.xml, wp-login.php, xmlrpc.php, readme.html, wp-json/, .well-known/security.txt).
  • Optional Nmap integration (--nmap and --nmap-deep): Calls system nmap for service version detection (-sV) and running basic HTTP/SSL NSE scripts.
  • Report export and change comparison (--save, --json, --diff): Lets you save full text and structured JSON reports, as well as compare a new scan against a previous JSON snapshot to track changes on the server.

Who This Script Is For

The tool is primarily intended for:

  • Webmasters and site owners who want to check domain availability, SSL certificate validity, open ports, and basic security headers in a few seconds.
  • System administrators and DevOps engineers who need a fast, portable CLI tool to verify server configuration, DNS records, and changes after updates.
  • Information security enthusiasts and students learning network protocols, HTTP headers, and the fundamentals of defensive reconnaissance on their own infrastructure.

Disclaimer

IMPORTANT USAGE NOTICE:

The Sniffer Lite v4.0 script is developed strictly for educational, diagnostic, and administrative purposes. It is intended for webmasters, system administrators, and system owners to inspect and improve the security of their own domains, servers, and network infrastructure, or environments for which explicit written permission from the owner has been granted.

Any misuse of this tool is strictly prohibited, including unauthorized scanning of third-party systems, networks, and web applications. The author assumes no responsibility for any damage, legal consequences, or misuse resulting from using this code in violation of law and ethical standards.

How to Use It (Companion Bash Commands)

1. Setup and executable permission

Save the code to sniffer_liteV4.0.py and make it executable:

Bash:

chmod +x sniffer_liteV4.0.py

2. Launching the interactive menu (recommended for quick work)

Running the script with no arguments (or with --menu) opens a numbered menu where you choose the scan mode, enter the target domain, and choose whether to save .txt and .json reports:

Bash:

python3 sniffer_liteV4.0.py
# or:
./sniffer_liteV4.0.py --menu

3. Direct CLI commands in the terminal

Bash:

# Basic domain check (17 key ports, SSL, HTTP headers)
python3 sniffer_liteV4.0.py perisareljic.name

# Check with DNS records (A, AAAA, NS, MX, TXT)
python3 sniffer_liteV4.0.py perisareljic.name --dns

# Scan the first 1,000 ports with Subdomain & Endpoint Recon
python3 sniffer_liteV4.0.py perisareljic.name 1k --recon

# Deep Nmap scan saving TXT and JSON reports
python3 sniffer_liteV4.0.py perisareljic.name common --dns --nmap-deep --save report.txt --json report.json

# Compare current server state against a previously saved JSON report
python3 sniffer_liteV4.0.py perisareljic.name 1k --recon --diff report.json

Complete Source Code (sniffer_liteV4.0.py)

#!/usr/bin/env python3
# ==============================================================================
# Title: Let me Script You: Sniffer Lite v4.0 (Recon & Pentest Arsenal Edition)
# Author: Perisa Reljic [ ▽ Ш ]
# Website: https://perisareljic.name | https://en.perisareljic.name
# ==============================================================================

import sys
import os
import json
import shutil
import socket
import ssl
import subprocess
import time
from datetime import datetime
from urllib.parse import urlparse, urljoin
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from concurrent.futures import ThreadPoolExecutor, as_completed

VERSION = "4.0"

COMMON_PORTS = {
    21: "FTP",
    22: "SSH",
    25: "SMTP",
    53: "DNS",
    80: "HTTP",
    110: "POP3",
    143: "IMAP",
    443: "HTTPS",
    465: "SMTPS",
    587: "Submission",
    993: "IMAPS",
    995: "POP3S",
    3306: "MySQL",
    5432: "PostgreSQL",
    6379: "Redis",
    8080: "HTTP-Alt",
    8443: "HTTPS-Alt",
}

WELL_KNOWN_PORTS = {
    20: "FTP-Data",
    21: "FTP",
    22: "SSH",
    23: "Telnet",
    25: "SMTP",
    53: "DNS",
    67: "DHCP",
    69: "TFTP",
    80: "HTTP",
    110: "POP3",
    111: "RPCbind",
    119: "NNTP",
    123: "NTP",
    135: "MSRPC",
    139: "NetBIOS",
    143: "IMAP",
    161: "SNMP",
    389: "LDAP",
    443: "HTTPS",
    445: "SMB",
    465: "SMTPS",
    514: "Syslog",
    515: "LPD",
    587: "Submission",
    631: "IPP",
    636: "LDAPS",
    873: "Rsync",
    993: "IMAPS",
    995: "POP3S",
    1080: "SOCKS",
}

HEADER_SPECS = [
    ("Strict-Transport-Security", "CORE", "Forces HTTPS-only browser connections"),
    ("X-Content-Type-Options", "CORE", "Prevents MIME-type sniffing"),
    ("X-Frame-Options", "CORE", "Mitigates clickjacking via iframes"),
    ("Referrer-Policy", "OPTIONAL", "Controls how much referrer info is sent"),
    ("Permissions-Policy", "OPTIONAL", "Restricts browser features (camera, mic, etc.)"),
    ("Content-Security-Policy", "OPTIONAL", "Controls script/resource sources (test carefully on WP)"),
]

COMMON_SUBDOMAINS = [
    "www",
    "mail",
    "webmail",
    "ftp",
    "cpanel",
    "plesk",
    "ns1",
    "ns2",
    "dev",
    "staging",
    "test",
    "api",
    "admin",
    "blog",
    "shop",
]

COMMON_ENDPOINTS = [
    "/robots.txt",
    "/sitemap.xml",
    "/sitemap_index.xml",
    "/wp-login.php",
    "/xmlrpc.php",
    "/readme.html",
    "/wp-json/",
    "/.well-known/security.txt",
]


class Reporter:
    """Collects terminal output lines, structured JSON data, and writes report files."""

    def __init__(self, save_path: str | None = None, json_path: str | None = None):
        self.save_path = save_path
        self.json_path = json_path
        self.lines: list[str] = []
        self.data: dict = {
            "tool": f"Sniffer Lite v{VERSION}",
            "author": "Perisa Reljic [ ▽ Ш ]",
            "timestamp": datetime.now().isoformat(),
            "target": {},
            "dns": {},
            "ports": [],
            "ssl": {},
            "http": {},
            "recon": {"subdomains": [], "endpoints": []},
            "nmap": {},
        }

    def out(self, text: str = ""):
        print(text)
        self.lines.append(text)

    def write_files(self):
        if self.save_path:
            parent = os.path.dirname(os.path.abspath(self.save_path))
            if parent and not os.path.exists(parent):
                os.makedirs(parent, exist_ok=True)
            with open(self.save_path, "w", encoding="utf-8") as f:
                f.write("\n".join(self.lines) + "\n")
            print(f"\n[Saved]: Text report written to '{os.path.abspath(self.save_path)}'")

        if self.json_path:
            parent = os.path.dirname(os.path.abspath(self.json_path))
            if parent and not os.path.exists(parent):
                os.makedirs(parent, exist_ok=True)
            with open(self.json_path, "w", encoding="utf-8") as f:
                json.dump(self.data, f, indent=2, ensure_ascii=False)
            print(f"[Saved]: JSON report written to '{os.path.abspath(self.json_path)}'")


def normalize_target(raw_target: str):
    """Extracts clean hostname and base URL from user input."""
    cleaned = raw_target.strip()
    if not cleaned:
        raise ValueError("Target domain or URL cannot be empty.")
    if not cleaned.startswith(("http://", "https://")):
        url = f"https://{cleaned}"
    else:
        url = cleaned
    parsed = urlparse(url)
    host = parsed.hostname
    if not host:
        raise ValueError(f"Invalid target: {raw_target}")
    base_url = f"{parsed.scheme or 'https'}://{host}"
    if parsed.port:
        base_url = f"{base_url}:{parsed.port}"
    return host, base_url


def resolve_host(host: str):
    """Resolves hostname to IPv4/IPv6 addresses."""
    try:
        infos = socket.getaddrinfo(host, None)
        ipv4 = sorted({i[4][0] for i in infos if i[0] == socket.AF_INET})
        ipv6 = sorted({i[4][0] for i in infos if i[0] == socket.AF_INET6})
        return ipv4, ipv6
    except socket.gaierror as e:
        print(f"[Error]: Could not resolve '{host}' -> {e}")
        sys.exit(1)


def query_dns_records(host: str, rep: Reporter):
    """Queries DNS records using dig/host if available, with socket fallback."""
    rep.out(f"\n[DNS] DNS & Host Resolution ({host})...")
    ipv4, ipv6 = resolve_host(host)
    rep.out(f"  A (IPv4)          : {', '.join(ipv4) if ipv4 else 'None'}")
    rep.out(f"  AAAA (IPv6)       : {', '.join(ipv6) if ipv6 else 'None'}")

    dns_info = {"A": ipv4, "AAAA": ipv6, "NS": [], "MX": [], "TXT": []}

    if shutil.which("dig"):
        for rtype in ("NS", "MX", "TXT"):
            try:
                p = subprocess.run(
                    ["dig", "+short", rtype, host],
                    capture_output=True,
                    text=True,
                    timeout=5,
                )
                vals = [line.strip() for line in p.stdout.splitlines() if line.strip()]
                dns_info[rtype] = vals
                rep.out(f"  {rtype:<17} : {' | '.join(vals) if vals else 'None'}")
            except Exception as e:
                rep.out(f"  {rtype:<17} : [Error: {e}]")
    elif shutil.which("host"):
        try:
            p = subprocess.run(
                ["host", "-a", host],
                capture_output=True,
                text=True,
                timeout=5,
            )
            relevant = [
                line.strip()
                for line in p.stdout.splitlines()
                if any(k in line for k in ("has address", "mail is handled", "name server", "descriptive text"))
            ]
            if relevant:
                for line in relevant[:12]:
                    rep.out(f"  {line}")
            else:
                rep.out("  No additional records returned via 'host'.")
        except Exception as e:
            rep.out(f"  [Error]: 'host' lookup failed -> {e}")
    else:
        rep.out("  [Tip]: Install 'dnsutils' (dig) for NS, MX, and TXT record lookups.")

    rep.data["dns"] = dns_info


def service_name_for_port(port: int) -> str:
    if port in COMMON_PORTS:
        return COMMON_PORTS[port]
    if port in WELL_KNOWN_PORTS:
        return WELL_KNOWN_PORTS[port]
    try:
        return socket.getservbyport(port, "tcp")
    except OSError:
        return "Unknown"


def grab_banner(sock: socket.socket, host: str, port: int) -> str:
    """Attempts lightweight banner grabbing on an open port."""
    try:
        sock.settimeout(1.5)
        if port in (80, 8080):
            req = f"HEAD / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode()
            sock.sendall(req)
        data = sock.recv(256)
        first_line = data.decode("utf-8", errors="ignore").splitlines()
        return first_line[0].strip() if first_line else ""
    except Exception:
        return ""


def scan_port(host: str, port: int, timeout: float = 1.0):
    """Checks if a TCP port is open and grabs a service banner if available."""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            if s.connect_ex((host, port)) == 0:
                service = service_name_for_port(port)
                banner = grab_banner(s, host, port)
                return port, service, banner
    except Exception:
        pass
    return None


def run_port_scan(host: str, ports: list[int], rep: Reporter, threads: int = 48, timeout: float = 1.0):
    rep.out(f"\n[1/3] TCP Port Scan ({len(ports)} ports | threads={threads}, timeout={timeout}s) on {host}...")
    open_ports = []
    start = time.time()

    with ThreadPoolExecutor(max_workers=threads) as executor:
        futures = {executor.submit(scan_port, host, p, timeout): p for p in ports}
        for future in as_completed(futures):
            res = future.result()
            if res:
                open_ports.append(res)

    elapsed = time.time() - start
    open_ports.sort(key=lambda x: x[0])

    if not open_ports:
        rep.out("  No open ports detected in scanned range.")
    else:
        rep.out(f"  {'PORT':<8} {'STATE':<8} {'SERVICE':<16} BANNER")
        rep.out("  " + "-" * 58)
        for port, service, banner in open_ports:
            rep.out(f"  {port:<8} {'OPEN':<8} {service:<16} {banner}")
            rep.data["ports"].append({
                "port": port,
                "state": "open",
                "service": service,
                "banner": banner,
            })
    rep.out(f"  Scan completed in {elapsed:.2f}s.")


def inspect_ssl(host: str, rep: Reporter, port: int = 443, timeout: float = 3.0):
    rep.out(f"\n[2/3] TLS/SSL Certificate Check ({host}:{port})...")
    ctx = ssl.create_default_context()
    try:
        with socket.create_connection((host, port), timeout=timeout) as raw_sock:
            with ctx.wrap_socket(raw_sock, server_hostname=host) as ssock:
                cert = ssock.getpeercert()
                cipher = ssock.cipher()
                subject = dict(x[0] for x in cert.get("subject", ()))
                issuer = dict(x[0] for x in cert.get("issuer", ()))
                san_list = [v for k, v in cert.get("subjectAltName", ()) if k == "DNS"]

                ssl_info = {
                    "protocol": cipher[1] if cipher else None,
                    "cipher": cipher[0] if cipher else None,
                    "subject_cn": subject.get("commonName"),
                    "issuer_org": issuer.get("organizationName"),
                    "not_before": cert.get("notBefore"),
                    "not_after": cert.get("notAfter"),
                    "san": san_list,
                }
                rep.data["ssl"] = ssl_info

                rep.out(f"  Protocol / Cipher : {cipher[1]} ({cipher[0]})")
                rep.out(f"  Issued To (CN)    : {subject.get('commonName', 'N/A')}")
                rep.out(f"  Issued By (Org)   : {issuer.get('organizationName', 'N/A')}")
                rep.out(f"  Valid From        : {cert.get('notBefore', 'N/A')}")
                rep.out(f"  Valid Until       : {cert.get('notAfter', 'N/A')}")
                if san_list:
                    rep.out(f"  SAN Domains       : {', '.join(san_list[:8])}")
    except Exception as e:
        rep.out(f"  [Info]: SSL check unavailable -> {e}")
        rep.data["ssl"] = {"error": str(e)}


def audit_cookies(headers: dict, rep: Reporter):
    """Checks Set-Cookie header flags if cookies are returned."""
    raw_cookies = []
    for k, v in headers.items():
        if k.lower() == "set-cookie":
            raw_cookies.append(v)
    if not raw_cookies:
        return []

    rep.out("\n  Cookie Hardening Audit:")
    cookie_findings = []
    for idx, c in enumerate(raw_cookies, start=1):
        parts = [p.strip() for p in c.split(";")]
        cname = parts[0].split("=", 1)[0] if parts else f"Cookie_{idx}"
        lower_c = c.lower()
        has_httponly = "httponly" in lower_c
        has_secure = "secure" in lower_c
        has_samesite = "samesite" in lower_c
        flags = []
        if has_httponly:
            flags.append("HttpOnly")
        if has_secure:
            flags.append("Secure")
        if has_samesite:
            flags.append("SameSite")
        flag_str = ", ".join(flags) if flags else "NONE"
        rep.out(f"    [COOKIE] {cname}: flags=[{flag_str}]")
        cookie_findings.append({
            "name": cname,
            "httponly": has_httponly,
            "secure": has_secure,
            "samesite": has_samesite,
        })
    return cookie_findings


def probe_http_options(url: str, rep: Reporter):
    """Checks allowed HTTP methods via OPTIONS request."""
    req = Request(
        url,
        method="OPTIONS",
        headers={"User-Agent": f"SnifferLite/{VERSION} (Authorized Diagnostic Probe)"},
    )
    try:
        with urlopen(req, timeout=4.0) as resp:
            allow = resp.headers.get("Allow") or resp.headers.get("Access-Control-Allow-Methods")
            if allow:
                rep.out(f"  Allowed Methods   : {allow}")
                return allow
    except Exception:
        pass
    return None


def inspect_http(url: str, rep: Reporter):
    rep.out(f"\n[3/3] HTTP Probe, Stack & Security Headers ({url})...")
    req = Request(
        url,
        method="GET",
        headers={"User-Agent": f"SnifferLite/{VERSION} (Authorized Diagnostic Probe)"},
    )
    try:
        with urlopen(req, timeout=5.0) as resp:
            status = resp.status
            final_url = resp.geturl()
            headers = dict(resp.headers.items())
            body_sample = resp.read(16384).decode("utf-8", errors="ignore")
    except HTTPError as e:
        status = e.code
        final_url = e.geturl()
        headers = dict(e.headers.items())
        body_sample = ""
    except URLError as e:
        rep.out(f"  [Error]: HTTP probe failed -> {e.reason}")
        rep.data["http"] = {"error": str(e.reason)}
        return

    rep.out(f"  HTTP Status       : {status}")
    rep.out(f"  Final URL         : {final_url}")
    rep.out(f"  Server            : {headers.get('Server', 'Hidden/Not disclosed')}")
    rep.out(f"  X-Powered-By      : {headers.get('X-Powered-By', 'Not disclosed')}")

    allow_methods = probe_http_options(url, rep)

    tech = []
    lower_body = body_sample.lower()
    if "wp-content" in lower_body or "wordpress" in lower_body:
        tech.append("WordPress")
    if "woocommerce" in lower_body:
        tech.append("WooCommerce")
    if "cloudflare" in headers.get("Server", "").lower() or "cf-ray" in {k.lower(): v for k, v in headers.items()}:
        tech.append("Cloudflare")
    if "plesk" in headers.get("X-Powered-By", "").lower():
        tech.append("Plesk")
    rep.out(f"  Detected Stack    : {', '.join(tech) if tech else 'Generic / Undetected'}")

    rep.out("\n  Security Headers Audit:")
    lower_headers = {k.lower(): v for k, v in headers.items()}
    missing_core = 0
    header_results = {}

    for h, tier, note in HEADER_SPECS:
        val = lower_headers.get(h.lower())
        if val:
            rep.out(f"    [OK]      [{tier:<8}] {h}: {val}")
            header_results[h] = {"status": "ok", "tier": tier, "value": val}
        else:
            if tier == "CORE":
                missing_core += 1
            rep.out(f"    [MISSING] [{tier:<8}] {h} — {note}")
            header_results[h] = {"status": "missing", "tier": tier, "note": note}

    cookies = audit_cookies(headers, rep)

    if missing_core == 0:
        summary_msg = "All core security headers are present."
    else:
        summary_msg = (
            f"{missing_core} core header(s) missing "
            "(informational for personal sites; tune on server when ready)."
        )
    rep.out(f"\n  Header Summary    : {summary_msg}")

    rep.data["http"] = {
        "status": status,
        "final_url": final_url,
        "server": headers.get("Server"),
        "x_powered_by": headers.get("X-Powered-By"),
        "allow_methods": allow_methods,
        "stack": tech,
        "headers": header_results,
        "cookies": cookies,
        "missing_core": missing_core,
    }


def check_single_subdomain(sub: str, domain: str, timeout: float = 1.5):
    fqdn = f"{sub}.{domain}"
    try:
        infos = socket.getaddrinfo(fqdn, None)
        ips = sorted({i[4][0] for i in infos if i[0] == socket.AF_INET})
        if ips:
            return fqdn, ips
    except socket.gaierror:
        pass
    return None


def check_single_endpoint(base_url: str, path: str, timeout: float = 3.5):
    target_url = urljoin(base_url + "/", path.lstrip("/"))
    req = Request(
        target_url,
        method="HEAD",
        headers={"User-Agent": f"SnifferLite/{VERSION} (Authorized Diagnostic Probe)"},
    )
    try:
        with urlopen(req, timeout=timeout) as resp:
            return path, resp.status, resp.geturl()
    except HTTPError as e:
        return path, e.code, target_url
    except Exception:
        return None


def run_recon_module(host: str, base_url: str, rep: Reporter, threads: int = 24):
    """Checks common subdomains and common web/WordPress endpoints."""
    rep.out(f"\n[RECON] Subdomain & Endpoint Reconnaissance ({host})...")

    found_subs = []
    with ThreadPoolExecutor(max_workers=min(threads, 24)) as ex:
        futs = {ex.submit(check_single_subdomain, sub, host): sub for sub in COMMON_SUBDOMAINS}
        for fut in as_completed(futs):
            res = fut.result()
            if res:
                found_subs.append(res)
    found_subs.sort(key=lambda x: x[0])

    if found_subs:
        rep.out("  Discovered Subdomains:")
        for fqdn, ips in found_subs:
            rep.out(f"    [FOUND] {fqdn:<28} -> {', '.join(ips)}")
            rep.data["recon"]["subdomains"].append({"subdomain": fqdn, "ips": ips})
    else:
        rep.out("  No common subdomains resolved.")

    interesting_endpoints = []
    with ThreadPoolExecutor(max_workers=min(threads, 16)) as ex:
        futs = {ex.submit(check_single_endpoint, base_url, p): p for p in COMMON_ENDPOINTS}
        for fut in as_completed(futs):
            res = fut.result()
            if res:
                path, code, _ = res
                if code != 404:
                    interesting_endpoints.append((path, code))
    interesting_endpoints.sort(key=lambda x: x[0])

    if interesting_endpoints:
        rep.out("  Interesting Endpoints (non-404):")
        for path, code in interesting_endpoints:
            rep.out(f"    [HTTP {code}] {path}")
            rep.data["recon"]["endpoints"].append({"path": path, "status": code})
    else:
        rep.out("  No non-404 endpoints detected among common paths.")


def run_nmap_mode(host: str, port_spec: str, deep: bool, rep: Reporter):
    """Runs system nmap if available."""
    rep.out(f"\n[NMAP] External Nmap Scan on {host}...")
    if not shutil.which("nmap"):
        rep.out("  [Error]: 'nmap' is not installed on this system.")
        rep.out("  Install via: sudo apt update && sudo apt install nmap")
        rep.data["nmap"] = {"error": "nmap not installed"}
        return

    cmd = ["nmap", "-T4"]
    if port_spec in ("1-1000", "top1000"):
        cmd.extend(["-p", "1-1000"])
    elif port_spec != "common":
        cmd.extend(["-p", port_spec])
    else:
        cmd.append("--top-ports=100")

    if deep:
        cmd.extend(["-sV", "--script=http-title,http-headers,ssl-cert"])
    else:
        cmd.append("-sV")

    cmd.append(host)
    rep.out(f"  Command           : {' '.join(cmd)}")
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=240)
        if p.returncode != 0 and p.stderr:
            rep.out(f"  [Warning]: {p.stderr.strip()}")
        for line in p.stdout.splitlines():
            rep.out(f"  {line}")
        rep.data["nmap"] = {
            "command": " ".join(cmd),
            "returncode": p.returncode,
            "output": p.stdout,
        }
    except subprocess.TimeoutExpired:
        rep.out("  [Error]: Nmap scan timed out.")
        rep.data["nmap"] = {"error": "timeout"}
    except Exception as e:
        rep.out(f"  [Error]: Nmap execution failed -> {e}")
        rep.data["nmap"] = {"error": str(e)}


def run_diff_mode(current_data: dict, previous_json_path: str, rep: Reporter):
    """Compares open ports, subdomains, and core headers against a previous JSON report."""
    rep.out(f"\n[DIFF] Comparing Current Scan against '{previous_json_path}'...")
    if not os.path.exists(previous_json_path):
        rep.out(f"  [Error]: Previous report file not found: {previous_json_path}")
        return

    try:
        with open(previous_json_path, "r", encoding="utf-8") as f:
            prev = json.load(f)
    except Exception as e:
        rep.out(f"  [Error]: Could not parse JSON report -> {e}")
        return

    prev_ports = {item["port"] for item in prev.get("ports", [])}
    curr_ports = {item["port"] for item in current_data.get("ports", [])}

    added_ports = sorted(curr_ports - prev_ports)
    closed_ports = sorted(prev_ports - curr_ports)

    rep.out(f"  New Open Ports    : {added_ports if added_ports else 'None'}")
    rep.out(f"  Closed/Missing    : {closed_ports if closed_ports else 'None'}")

    prev_subs = {item["subdomain"] for item in prev.get("recon", {}).get("subdomains", [])}
    curr_subs = {item["subdomain"] for item in current_data.get("recon", {}).get("subdomains", [])}
    added_subs = sorted(curr_subs - prev_subs)
    removed_subs = sorted(prev_subs - curr_subs)

    if prev_subs or curr_subs:
        rep.out(f"  New Subdomains    : {added_subs if added_subs else 'None'}")
        rep.out(f"  Removed Subdomains: {removed_subs if removed_subs else 'None'}")

    prev_missing = prev.get("http", {}).get("missing_core")
    curr_missing = current_data.get("http", {}).get("missing_core")
    if prev_missing is not None and curr_missing is not None:
        rep.out(f"  Missing Core Hdrs : {prev_missing} (previous) -> {curr_missing} (current)")


def parse_ports(port_arg: str) -> list[int]:
    cleaned = port_arg.strip().lower()
    if cleaned in ("common", "default"):
        return sorted(COMMON_PORTS.keys())
    if cleaned in ("1k", "1000", "top1000"):
        return list(range(1, 1001))
    if "-" in cleaned:
        start, end = map(int, cleaned.split("-", 1))
        if not (1 <= start <= end <= 65535):
            raise ValueError("Port range must be between 1 and 65535.")
        return list(range(start, end + 1))
    return sorted({int(p.strip()) for p in cleaned.split(",") if p.strip()})


def print_usage():
    print("==================================================================")
    print(f"  Let me Script You: Sniffer Lite v{VERSION} | Perisa Reljic [ ▽ Ш ]")
    print("==================================================================")
    print("Usage:")
    print(f"  python3 sniffer_liteV{VERSION}.py --menu")
    print(f"  python3 sniffer_liteV{VERSION}.py <domain_or_url> [ports|1k|1-1000] [options]")
    print("\nOptions:")
    print("  --menu             Launch interactive numbered menu")
    print("  --dns              Include A, AAAA, NS, MX, and TXT DNS lookups")
    print("  --recon            Check common subdomains & endpoints/WordPress paths")
    print("  --nmap             Run external 'nmap -sV' service detection")
    print("  --nmap-deep        Run 'nmap -sV' with HTTP/SSL NSE scripts")
    print("  --threads <N>      Number of worker threads (default: 48)")
    print("  --timeout <SEC>    Socket timeout in seconds (default: 1.0)")
    print("  --save <file>      Save full text report to file")
    print("  --json <file>      Save structured JSON report to file")
    print("  --diff <json>      Compare scan results against a previous JSON report")


def parse_cli_args(argv: list[str]):
    raw_target = None
    port_spec = "common"
    use_dns = False
    use_recon = False
    use_nmap = False
    nmap_deep = False
    threads = 48
    timeout = 1.0
    save_path = None
    json_path = None
    diff_path = None

    i = 0
    while i < len(argv):
        arg = argv[i]
        if arg == "--dns":
            use_dns = True
        elif arg == "--recon":
            use_recon = True
        elif arg == "--nmap":
            use_nmap = True
        elif arg == "--nmap-deep":
            use_nmap = True
            nmap_deep = True
        elif arg == "--threads":
            if i + 1 >= len(argv):
                raise ValueError("--threads requires a numeric value.")
            i += 1
            threads = int(argv[i])
        elif arg == "--timeout":
            if i + 1 >= len(argv):
                raise ValueError("--timeout requires a numeric value.")
            i += 1
            timeout = float(argv[i])
        elif arg == "--save":
            if i + 1 >= len(argv):
                raise ValueError("--save requires a file path argument.")
            i += 1
            save_path = argv[i]
        elif arg == "--json":
            if i + 1 >= len(argv):
                raise ValueError("--json requires a file path argument.")
            i += 1
            json_path = argv[i]
        elif arg == "--diff":
            if i + 1 >= len(argv):
                raise ValueError("--diff requires a previous JSON report path.")
            i += 1
            diff_path = argv[i]
        elif not arg.startswith("-") and raw_target is None:
            raw_target = arg
        elif not arg.startswith("-") and port_spec == "common":
            port_spec = arg
        else:
            raise ValueError(f"Unknown or misplaced argument: '{arg}'")
        i += 1

    if not raw_target:
        raise ValueError("Missing target domain or URL.")
    if threads < 1 or threads > 256:
        raise ValueError("Threads must be between 1 and 256.")
    if timeout <= 0 or timeout > 30:
        raise ValueError("Timeout must be between 0 and 30 seconds.")

    return (
        raw_target,
        port_spec,
        use_dns,
        use_recon,
        use_nmap,
        nmap_deep,
        threads,
        timeout,
        save_path,
        json_path,
        diff_path,
    )


def run_interactive_menu():
    print("==================================================================")
    print(f"  Let me Script You: Sniffer Lite v{VERSION} | Perisa Reljic [ ▽ Ш ]")
    print("==================================================================")
    print("Select an option:")
    print("  [1] Quick scan (17 ports, SSL, HTTP headers, cookies)")
    print("  [2] Scan + DNS records (A, AAAA, NS, MX, TXT)")
    print("  [3] Scan + Subdomain & Endpoint/WP Recon")
    print("  [4] Scan 1,000 ports (1-1000, fast mode)")
    print("  [5] Scan + Nmap services (-sV)")
    print("  [6] Scan + Deep Nmap (-sV + HTTP/SSL scripts)")
    print("  [7] Full Arsenal (DNS + Recon + 1000 ports + Deep Nmap)")
    print("  [8] Custom ports / range")
    print("  [0] Exit")

    choice = input("\nOption number [1]: ").strip() or "1"
    if choice == "0":
        print("Exiting.")
        sys.exit(0)

    use_dns = choice in ("2", "7")
    use_recon = choice in ("3", "7")
    port_spec = "1k" if choice in ("4", "7") else "common"
    use_nmap = choice in ("5", "6", "7")
    nmap_deep = choice in ("6", "7")
    threads = 80 if port_spec == "1k" else 48
    timeout = 0.75 if port_spec == "1k" else 1.0

    if choice == "8":
        custom_ports = input("Enter ports (e.g. 80,443,22, 1-1000 or 1k) [common]: ").strip()
        if custom_ports:
            port_spec = custom_ports

    raw_target = input("Enter target domain or URL: ").strip()
    host, url = normalize_target(raw_target)
    ports = parse_ports(port_spec)

    diff_input = input("Compare against previous JSON report (path or Enter to skip): ").strip()
    diff_path = diff_input or None

    save_choice = input("Save report to TXT file? (y/n) [n]: ").strip().lower()
    save_path = None
    json_path = None
    safe_host = host.replace(".", "_")
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    if save_choice in ("y", "yes", "da", "d"):
        default_name = f"report_{safe_host}_{stamp}.txt"
        custom_name = input(f"TXT file name [{default_name}]: ").strip()
        save_path = custom_name or default_name

    json_choice = input("Also save JSON report (for --diff / automation)? (y/n) [n]: ").strip().lower()
    if json_choice in ("y", "yes", "da", "d"):
        default_json = f"report_{safe_host}_{stamp}.json"
        custom_json = input(f"JSON file name [{default_json}]: ").strip()
        json_path = custom_json or default_json

    return (
        raw_target,
        host,
        url,
        port_spec,
        ports,
        use_dns,
        use_recon,
        use_nmap,
        nmap_deep,
        threads,
        timeout,
        save_path,
        json_path,
        diff_path,
    )


def execute_scan(
    raw_target,
    host,
    url,
    port_spec,
    ports,
    use_dns,
    use_recon,
    use_nmap,
    nmap_deep,
    threads,
    timeout,
    save_path,
    json_path,
    diff_path,
):
    rep = Reporter(save_path=save_path, json_path=json_path)
    ipv4, ipv6 = resolve_host(host)

    rep.data["target"] = {
        "input": raw_target,
        "host": host,
        "url": url,
        "ipv4": ipv4,
        "ipv6": ipv6,
        "port_spec": port_spec,
    }

    rep.out("==================================================================")
    rep.out(f"  Let me Script You: Sniffer Lite v{VERSION} | Perisa Reljic [ ▽ Ш ]")
    rep.out("==================================================================")
    rep.out(f"Timestamp   : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    rep.out(f"Target Host : {host}")
    rep.out(f"IPv4        : {', '.join(ipv4) if ipv4 else 'None'}")
    if ipv6:
        rep.out(f"IPv6        : {', '.join(ipv6)}")

    if use_dns:
        query_dns_records(host, rep)

    run_port_scan(host, ports, rep, threads=threads, timeout=timeout)

    if 443 in ports:
        inspect_ssl(host, rep, 443, timeout=max(timeout, 2.5))

    inspect_http(url, rep)

    if use_recon:
        run_recon_module(host, url, rep, threads=threads)

    if use_nmap:
        run_nmap_mode(host, port_spec, nmap_deep, rep)

    if diff_path:
        run_diff_mode(rep.data, diff_path, rep)

    rep.out("\n==================================================================")
    rep.write_files()


if __name__ == "__main__":
    if len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] in ("--menu", "-m")):
        try:
            data = run_interactive_menu()
            execute_scan(*data)
        except ValueError as err:
            print(f"[Error]: {err}")
            sys.exit(1)
    elif len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help"):
        print_usage()
        sys.exit(0)
    else:
        try:
            (
                raw_target,
                port_spec,
                use_dns,
                use_recon,
                use_nmap,
                nmap_deep,
                threads,
                timeout,
                save_path,
                json_path,
                diff_path,
            ) = parse_cli_args(sys.argv[1:])
            host, url = normalize_target(raw_target)
            ports = parse_ports(port_spec)
            execute_scan(
                raw_target,
                host,
                url,
                port_spec,
                ports,
                use_dns,
                use_recon,
                use_nmap,
                nmap_deep,
                threads,
                timeout,
                save_path,
                json_path,
                diff_path,
            )
        except ValueError as err:
            print(f"[Error]: {err}")
            sys.exit(1)

Source Code & Documentation:

The complete source code (sniffer_liteV4.0.py) and the accompanying README file are available for download on my GitHub repository: