network security

Scanning Network with Nmap Advanced Techniques

Performs advanced network reconnaissance using Nmap's scripting engine, timing controls, evasion techniques, and output parsing to discover hosts, enumerate services, detect vulnerabilities, and fingerprint operating systems across authorized target networks.

network-securitynmapport-scanningreconnaissanceservice-enumeration
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • Performing comprehensive asset discovery across large enterprise networks during authorized assessments
  • Enumerating service versions and configurations to identify outdated or vulnerable software
  • Bypassing firewall rules and IDS during authorized penetration tests using scan evasion techniques
  • Scripting automated vulnerability checks using the Nmap Scripting Engine (NSE)
  • Generating structured scan output for integration into vulnerability management pipelines

Do not use against networks without explicit written authorization, on production systems during peak hours without approval, or to perform denial-of-service through aggressive scan timing.

Prerequisites

  • Nmap 7.90+ installed (nmap --version to verify)
  • Root/sudo privileges for SYN scans, OS detection, and raw packet techniques
  • Written authorization specifying in-scope IP ranges and any excluded hosts
  • Network access to target ranges (VPN, direct connection, or jump host)
  • Familiarity with TCP/IP protocols and common port assignments

Workflow

Step 1: Host Discovery with Multiple Probes

Use layered discovery to find live hosts even when ICMP is blocked:

# ARP discovery for local subnet (most reliable on LAN)
nmap -sn -PR 192.168.1.0/24 -oA discovery_arp
 
# Combined ICMP + TCP + UDP probes for remote networks
nmap -sn -PE -PP -PS21,22,25,80,443,445,3389,8080 -PU53,161,500 10.0.0.0/16 -oA discovery_combined
 
# List scan to resolve DNS names without sending packets to targets
nmap -sL 10.0.0.0/24 -oN dns_resolution.txt

Consolidate results into a live hosts file:

grep "Host:" discovery_combined.gnmap | awk '{print $2}' | sort -t. -k1,1n -k2,2n -k3,3n -k4,4n > live_hosts.txt

Step 2: Port Scanning with Timing and Performance Tuning

# Full TCP SYN scan with optimized timing
nmap -sS -p- --min-rate 5000 --max-retries 2 -T4 -iL live_hosts.txt -oA full_tcp_scan
 
# Top 1000 UDP ports with version detection
nmap -sU --top-ports 1000 --version-intensity 0 -T4 -iL live_hosts.txt -oA udp_scan
 
# Specific port ranges for targeted assessment
nmap -sS -p 1-1024,3306,5432,6379,8080-8090,9200,27017 -iL live_hosts.txt -oA targeted_ports

Step 3: Service Version Detection and OS Fingerprinting

# Aggressive service detection with version intensity
nmap -sV --version-intensity 5 -sC -O --osscan-guess -p <open_ports> -iL live_hosts.txt -oA service_enum
 
# Specific service probing for ambiguous ports
nmap -sV --version-all -p 8443 --script ssl-cert,http-title,http-server-header <target> -oN service_detail.txt

Step 4: NSE Vulnerability Scanning

# Run vulnerability detection scripts
nmap --script vuln -p <open_ports> -iL live_hosts.txt -oA vuln_scan
 
# Target specific vulnerabilities
nmap --script smb-vuln-ms17-010,smb-vuln-ms08-067 -p 445 -iL live_hosts.txt -oA smb_vulns
nmap --script ssl-heartbleed,ssl-poodle,ssl-ccs-injection -p 443,8443 -iL live_hosts.txt -oA ssl_vulns
 
# Brute force default credentials on discovered services
nmap --script http-default-accounts,ftp-anon,ssh-auth-methods -p 21,22,80,8080 -iL live_hosts.txt -oA default_creds

Step 5: Firewall Evasion Techniques

# Fragment packets to evade simple packet inspection
nmap -sS -f --mtu 24 -p 80,443 <target> -oN fragmented_scan.txt
 
# Use decoy addresses to obscure scan origin
nmap -sS -D RND:10 -p 80,443 <target> -oN decoy_scan.txt
 
# Spoof source port as DNS (53) to bypass poorly configured firewalls
nmap -sS --source-port 53 -p 1-1024 <target> -oN spoofed_port_scan.txt
 
# Idle scan using a zombie host (completely stealthy)
nmap -sI <zombie_host> -p 80,443,445 <target> -oN idle_scan.txt
 
# Slow scan to evade IDS rate-based detection
nmap -sS -T1 --max-rate 10 -p 1-1024 <target> -oA stealth_scan

Step 6: Output Parsing and Reporting

# Convert XML output to HTML report
xsltproc full_tcp_scan.xml -o scan_report.html
 
# Extract open ports per host from grepable output
grep "Ports:" full_tcp_scan.gnmap | awk -F'Ports: ' '{print $1 $2}' > open_ports_summary.txt
 
# Parse XML with nmap-parse-output for structured data
nmap-parse-output full_tcp_scan.xml hosts-to-port 445
 
# Import into Metasploit database
msfconsole -q -x "db_import full_tcp_scan.xml; hosts; services; exit"
 
# Generate CSV for vulnerability management tools
nmap-parse-output full_tcp_scan.xml csv > scan_results.csv

Key Concepts

Term Definition
SYN Scan (-sS) Half-open TCP scan that sends SYN packets and analyzes responses without completing the three-way handshake, making it faster and stealthier than connect scans
NSE (Nmap Scripting Engine) Lua-based scripting framework built into Nmap that enables vulnerability detection, brute forcing, service discovery, and custom automation
Timing Templates (-T0 to -T5) Predefined scan speed profiles ranging from Paranoid (T0) to Insane (T5), controlling probe parallelism, timeout values, and inter-probe delays
Idle Scan (-sI) Advanced scan technique that uses a zombie host's IP ID sequence to port scan a target without sending packets from the scanner's own IP address
Version Intensity Controls how many probes Nmap sends to determine service versions, ranging from 0 (light) to 9 (all probes), trading speed for accuracy
Grepable Output (-oG) Legacy Nmap output format designed for easy parsing with grep, awk, and sed for scripted analysis of scan results

Tools & Systems

  • Nmap 7.90+: Core scanning engine with NSE scripting, OS detection, version probing, and multiple output formats
  • nmap-parse-output: Community tool for parsing Nmap XML output into structured formats (CSV, JSON, host lists)
  • Ndiff: Nmap utility for comparing two scan results to identify changes in network state over time
  • Zenmap: Official Nmap GUI providing visual network topology mapping and scan profile management
  • Metasploit Framework: Imports Nmap XML output for direct correlation of scan results with exploit modules

Common Scenarios

Scenario: Enterprise Network Asset Discovery and Vulnerability Baseline

Context: A security team needs to establish a vulnerability baseline for a corporate network spanning 10.0.0.0/8 with approximately 5,000 active hosts. Scanning must complete within a weekend maintenance window with minimal network disruption.

Approach:

  1. Run layered host discovery using ARP (local subnets), TCP SYN (ports 22,80,443,445,3389), and ICMP echo probes across all /24 subnets
  2. Perform a full TCP SYN scan on discovered hosts using --min-rate 5000 and -T4 to complete within the window
  3. Run service version detection and default NSE scripts on all open ports
  4. Execute targeted NSE vulnerability scripts for critical services (SMB, SSL/TLS, HTTP)
  5. Parse XML output to generate per-subnet CSV reports and import into the vulnerability management platform
  6. Schedule Ndiff comparisons against future scans to track remediation progress

Pitfalls:

  • Setting --min-rate too high on congested network segments causing packet loss and false negatives
  • Running -T5 (Insane) timing on production networks, potentially overwhelming older network devices
  • Forgetting to scan UDP ports, missing critical services like SNMP (161), DNS (53), and TFTP (69)
  • Not saving output in XML format (-oX or -oA), losing structured data for downstream tool integration

Output Format

## Nmap Scan Summary
 
**Scan Profile**: Full TCP + Top 200 UDP + Service Enumeration
**Target Range**: 10.10.0.0/16
**Hosts Discovered**: 347 live hosts
**Scan Duration**: 2h 14m
 
### Critical Findings
 
| Host | Port | Service | Version | Vulnerability |
|------|------|---------|---------|---------------|
| 10.10.5.23 | 445/tcp | SMB | Windows Server 2012 R2 | MS17-010 (EternalBlue) |
| 10.10.8.100 | 443/tcp | Apache httpd | 2.4.29 | CVE-2021-41773 (Path Traversal) |
| 10.10.12.5 | 3306/tcp | MySQL | 5.6.24 | CVE-2016-6662 (RCE) |
| 10.10.3.77 | 161/udp | SNMP | v2c | Public community string |
 
### Recommendations
1. Patch MS17-010 on 10.10.5.23 immediately -- Critical RCE vulnerability
2. Upgrade Apache httpd to 2.4.58+ on 10.10.8.100
3. Upgrade MySQL to 8.0.x on 10.10.12.5 and restrict bind address
4. Change SNMP community strings from "public" on 10.10.3.77
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md2.0 KB

API Reference: Scanning Network with Nmap Advanced

python-nmap Library

Installation

pip install python-nmap

Requires Nmap binary installed on the system (nmap must be in PATH).

Core Classes

nmap.PortScanner()

Main scanner class wrapping the Nmap command-line tool.

Method Parameters Returns Description
scan() hosts, ports, arguments dict Execute Nmap scan with given arguments
all_hosts() - list[str] List of all scanned host IPs
nmap_version() - tuple Installed Nmap version
command_line() - str Nmap command that was executed

Scanner Result Access

scanner[host].state()              # Host state: 'up' or 'down'
scanner[host].all_protocols()      # ['tcp', 'udp']
scanner[host][proto].keys()        # List of port numbers
scanner[host][proto][port]         # Port info dict with keys: state, name, product, version
scanner[host].hostnames()          # [{'name': 'hostname', 'type': 'PTR'}]
scanner[host]['osmatch']           # OS detection results

Common Nmap Arguments

Argument Purpose
-sS TCP SYN scan (half-open, requires root)
-sV Service version detection
-sC Run default NSE scripts
-O OS fingerprinting
-sn Host discovery only (no port scan)
--script vuln Run vulnerability detection scripts
-T0 to -T5 Timing templates (paranoid to insane)
--min-rate N Minimum packets per second
-PE -PP -PS ICMP echo, timestamp, TCP SYN discovery probes
-oX file Output results in XML format

Output Parsing

scanner.csv()           # CSV-formatted scan results
scanner.scaninfo()      # Scan metadata (type, services scanned)
scanner.scanstats()     # Timing and host statistics

References

Scripts 1

agent.py7.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Automated network scanning agent using python-nmap for authorized assessments."""

import nmap
import json
import csv
import sys
import os
import argparse
from datetime import datetime


def discover_hosts(scanner, target, timing="T4"):
    """Run host discovery using multiple probe techniques."""
    print(f"[*] Discovering live hosts on {target}...")
    scanner.scan(hosts=target, arguments=f"-sn -PE -PP -PS22,80,443,445,3389 -{timing}")
    hosts = []
    for host in scanner.all_hosts():
        state = scanner[host].state()
        if state == "up":
            hosts.append(host)
            hostnames = [h["name"] for h in scanner[host].hostnames() if h["name"]]
            hostname_str = ", ".join(hostnames) if hostnames else "N/A"
            print(f"  [+] {host} ({hostname_str}) - {state}")
    print(f"[*] Discovered {len(hosts)} live hosts")
    return hosts


def scan_ports(scanner, hosts, ports="1-1024", timing="T4"):
    """Run SYN scan on discovered hosts for specified ports."""
    results = {}
    target_str = " ".join(hosts) if isinstance(hosts, list) else hosts
    print(f"\n[*] Scanning ports {ports} on {len(hosts) if isinstance(hosts, list) else 1} host(s)...")
    scanner.scan(hosts=target_str, ports=ports, arguments=f"-sS -{timing} --min-rate 3000 --max-retries 2")
    for host in scanner.all_hosts():
        results[host] = []
        for proto in scanner[host].all_protocols():
            ports_list = sorted(scanner[host][proto].keys())
            for port in ports_list:
                port_info = scanner[host][proto][port]
                if port_info["state"] == "open":
                    results[host].append({
                        "port": port,
                        "protocol": proto,
                        "state": port_info["state"],
                        "service": port_info.get("name", "unknown"),
                        "version": port_info.get("version", ""),
                        "product": port_info.get("product", ""),
                    })
                    print(f"  [+] {host}:{port}/{proto} - {port_info.get('name', '?')} "
                          f"{port_info.get('product', '')} {port_info.get('version', '')}")
    return results


def service_version_scan(scanner, host, open_ports):
    """Run aggressive service version detection on open ports."""
    port_str = ",".join(str(p["port"]) for p in open_ports)
    print(f"\n[*] Running service version detection on {host} ports {port_str}...")
    scanner.scan(hosts=host, ports=port_str, arguments="-sV --version-intensity 5 -sC -O --osscan-guess")
    info = {"os_matches": [], "services": []}
    if host in scanner.all_hosts():
        if "osmatch" in scanner[host]:
            for os_match in scanner[host]["osmatch"][:3]:
                info["os_matches"].append({"name": os_match["name"], "accuracy": os_match["accuracy"]})
        for proto in scanner[host].all_protocols():
            for port in sorted(scanner[host][proto].keys()):
                svc = scanner[host][proto][port]
                info["services"].append({
                    "port": port, "protocol": proto, "service": svc.get("name", ""),
                    "product": svc.get("product", ""), "version": svc.get("version", ""),
                    "extrainfo": svc.get("extrainfo", ""),
                })
    return info


def vuln_scan(scanner, host, open_ports):
    """Run NSE vulnerability scripts against open ports."""
    port_str = ",".join(str(p["port"]) for p in open_ports)
    print(f"\n[*] Running vulnerability scripts on {host}...")
    scanner.scan(hosts=host, ports=port_str, arguments="--script vuln")
    vulns = []
    if host in scanner.all_hosts():
        for proto in scanner[host].all_protocols():
            for port in scanner[host][proto]:
                svc = scanner[host][proto][port]
                if "script" in svc:
                    for script_name, output in svc["script"].items():
                        if "VULNERABLE" in str(output).upper() or "CVE-" in str(output).upper():
                            vulns.append({"host": host, "port": port, "script": script_name, "output": output[:500]})
                            print(f"  [!] VULN {host}:{port} - {script_name}")
    return vulns


def generate_report(discovery, port_results, version_info, vulnerabilities, output_dir):
    """Generate JSON and CSV reports from scan results."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    report = {
        "scan_date": datetime.now().isoformat(),
        "hosts_discovered": len(discovery),
        "hosts": discovery,
        "port_scan_results": port_results,
        "version_info": version_info,
        "vulnerabilities": vulnerabilities,
    }
    json_path = os.path.join(output_dir, f"scan_report_{timestamp}.json")
    with open(json_path, "w") as f:
        json.dump(report, f, indent=2, default=str)
    print(f"\n[*] JSON report saved to {json_path}")

    csv_path = os.path.join(output_dir, f"open_ports_{timestamp}.csv")
    with open(csv_path, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["Host", "Port", "Protocol", "Service", "Product", "Version"])
        for host, ports in port_results.items():
            for p in ports:
                writer.writerow([host, p["port"], p["protocol"], p["service"], p["product"], p["version"]])
    print(f"[*] CSV report saved to {csv_path}")
    return json_path, csv_path


def main():
    parser = argparse.ArgumentParser(description="Nmap Advanced Network Scanner Agent")
    parser.add_argument("target", help="Target IP, CIDR range, or hostname")
    parser.add_argument("-p", "--ports", default="1-1024", help="Port range to scan (default: 1-1024)")
    parser.add_argument("-t", "--timing", default="T4", choices=["T0", "T1", "T2", "T3", "T4", "T5"])
    parser.add_argument("--vuln", action="store_true", help="Run NSE vulnerability scripts")
    parser.add_argument("--version-scan", action="store_true", help="Run service version detection")
    parser.add_argument("-o", "--output", default=".", help="Output directory for reports")
    args = parser.parse_args()

    os.makedirs(args.output, exist_ok=True)
    scanner = nmap.PortScanner()
    print(f"[*] Nmap version: {scanner.nmap_version()}")
    print(f"[*] Target: {args.target} | Ports: {args.ports} | Timing: {args.timing}")

    hosts = discover_hosts(scanner, args.target, args.timing)
    if not hosts:
        print("[-] No live hosts found. Exiting.")
        sys.exit(0)

    port_results = scan_ports(scanner, hosts, args.ports, args.timing)
    version_info, vulnerabilities = {}, []

    for host, open_ports in port_results.items():
        if not open_ports:
            continue
        if args.version_scan:
            version_info[host] = service_version_scan(scanner, host, open_ports)
        if args.vuln:
            vulnerabilities.extend(vuln_scan(scanner, host, open_ports))

    generate_report(hosts, port_results, version_info, vulnerabilities, args.output)
    total_open = sum(len(p) for p in port_results.values())
    print(f"\n[*] Scan complete: {len(hosts)} hosts, {total_open} open ports, {len(vulnerabilities)} vulns found")


if __name__ == "__main__":
    main()
Keep exploring