Skip to content

Nmap Cheat Sheet

Overview

Nmap (Network Mapper) is the world's most widely used network discovery and security auditing tool, designed to rapidly scan large networks and determine which hosts are available, what services they offer, what operating systems they run, what type of packet filters or firewalls are in use, and dozens of other characteristics. Originally written by Gordon Lyon (Fyodor) and first released in 1997, Nmap has evolved into the de facto standard for network reconnaissance and security assessment, providing comprehensive capabilities for network administrators, security professionals, and penetration testers to understand and secure their network infrastructure.

The core strength of Nmap lies in its sophisticated port scanning algorithms and service detection capabilities, which can identify open ports, running services, and system characteristics across diverse network environments. Nmap employs various scanning techniques including TCP connect scans, SYN stealth scans, UDP scans, and specialized techniques for firewall and intrusion detection system evasion. The tool's advanced service and version detection engine can identify specific software versions, operating system details, and device types through intelligent fingerprinting and banner analysis, providing detailed intelligence about target systems and their security posture.

Nmap's extensive feature set includes scriptable interaction through the Nmap Scripting Engine (NSE), which provides hundreds of pre-built scripts for vulnerability detection, service enumeration, and advanced reconnaissance tasks. The platform supports multiple output formats for integration with other security tools, offers timing and performance optimization options for different network environments, and includes advanced features for IPv6 scanning, firewall evasion, and stealth reconnaissance. With its proven reliability, comprehensive documentation, and active development community, Nmap remains the essential tool for network discovery and security assessment across organizations worldwide.

Installation

Ubuntu/Debian Installation

Installing Nmap on Ubuntu/Debian systems:

bash
# Update system packages
sudo apt update && sudo apt upgrade -y

# Install Nmap from repositories
sudo apt install -y nmap

# Install additional tools
sudo apt install -y ncat nping ndiff

# Verify installation
nmap --version

# Install latest version from source
sudo apt install -y build-essential libssl-dev libpcap-dev
wget https://nmap.org/dist/nmap-7.94.tar.bz2
tar -xjf nmap-7.94.tar.bz2
cd nmap-7.94
./configure
make
sudo make install

# Install Zenmap (GUI)
sudo apt install -y zenmap

# Verify NSE scripts
ls /usr/share/nmap/scripts/ | wc -l
nmap --script-help all | head -20

CentOS/RHEL Installation

bash
# Install EPEL repository
sudo yum install -y epel-release

# Install Nmap
sudo yum install -y nmap nmap-ncat

# Install development tools for source installation
sudo yum groupinstall -y "Development Tools"
sudo yum install -y openssl-devel libpcap-devel

# Build from source
wget https://nmap.org/dist/nmap-7.94.tar.bz2
tar -xjf nmap-7.94.tar.bz2
cd nmap-7.94
./configure
make
sudo make install

# Verify installation
nmap --version

macOS Installation

bash
# Install using Homebrew
brew install nmap

# Install using MacPorts
sudo port install nmap

# Download installer from nmap.org
# https://nmap.org/download.html#macosx

# Verify installation
nmap --version

# Install additional tools
brew install ncat

Windows Installation

bash
# Download Windows installer
# https://nmap.org/download.html#windows

# Install using Chocolatey
choco install nmap

# Install using Scoop
scoop install nmap

# Verify installation
nmap --version

# Install Zenmap GUI
# Included in Windows installer package

Docker Installation

Running Nmap in Docker:

bash
# Pull official Nmap image
docker pull instrumentisto/nmap

# Run basic scan
docker run --rm instrumentisto/nmap -sn 192.168.1.0/24

# Run with custom scripts
docker run --rm -v $(pwd):/data instrumentisto/nmap \
    --script vuln -oA /data/scan_results 192.168.1.100

# Create custom Dockerfile
cat > Dockerfile.nmap << 'EOF'
FROM alpine:latest

# Install Nmap and dependencies
RUN apk add --no-cache nmap nmap-scripts nmap-ncat

# Create working directory
WORKDIR /scans

# Set default command
CMD ["nmap", "--help"]
EOF

# Build custom image
docker build -f Dockerfile.nmap -t nmap-custom .

# Run custom image
docker run --rm -it nmap-custom nmap -sn 192.168.1.0/24

Basic Usage

Host Discovery

Discovering hosts on the network:

bash
# Ping scan (host discovery only)
nmap -sn 192.168.1.0/24

# ARP scan (local network)
nmap -PR 192.168.1.0/24

# ICMP echo scan
nmap -PE 192.168.1.0/24

# ICMP timestamp scan
nmap -PP 192.168.1.0/24

# ICMP netmask scan
nmap -PM 192.168.1.0/24

# TCP SYN ping
nmap -PS22,80,443 192.168.1.0/24

# TCP ACK ping
nmap -PA22,80,443 192.168.1.0/24

# UDP ping
nmap -PU53,161,162 192.168.1.0/24

# Skip host discovery (treat all hosts as online)
nmap -Pn 192.168.1.100

# List scan (no ping, no port scan)
nmap -sL 192.168.1.0/24

# Traceroute
nmap --traceroute 192.168.1.100

# Discover hosts with specific ports open
nmap -p 22 --open 192.168.1.0/24

Port Scanning

Different port scanning techniques:

bash
# TCP SYN scan (default, requires root)
nmap -sS 192.168.1.100

# TCP connect scan (no root required)
nmap -sT 192.168.1.100

# UDP scan
nmap -sU 192.168.1.100

# TCP ACK scan (firewall detection)
nmap -sA 192.168.1.100

# TCP Window scan
nmap -sW 192.168.1.100

# TCP Maimon scan
nmap -sM 192.168.1.100

# TCP FIN scan
nmap -sF 192.168.1.100

# TCP NULL scan
nmap -sN 192.168.1.100

# TCP Xmas scan
nmap -sX 192.168.1.100

# SCTP INIT scan
nmap -sY 192.168.1.100

# IP protocol scan
nmap -sO 192.168.1.100

# Scan specific ports
nmap -p 22,80,443 192.168.1.100

# Scan port ranges
nmap -p 1-1000 192.168.1.100
nmap -p- 192.168.1.100  # All ports

# Scan most common ports
nmap --top-ports 1000 192.168.1.100

# Fast scan (100 most common ports)
nmap -F 192.168.1.100

Service and Version Detection

Identifying services and versions:

bash
# Service version detection
nmap -sV 192.168.1.100

# Aggressive version detection
nmap -sV --version-intensity 9 192.168.1.100

# Light version detection
nmap -sV --version-intensity 0 192.168.1.100

# Service detection with all probes
nmap -sV --version-all 192.168.1.100

# Operating system detection
nmap -O 192.168.1.100

# Aggressive OS detection
nmap -O --osscan-guess 192.168.1.100

# Combined service and OS detection
nmap -A 192.168.1.100

# Detect service info for specific ports
nmap -sV -p 80,443 192.168.1.100

# Banner grabbing
nmap -sV --script banner 192.168.1.100

# Service fingerprinting
nmap -sV --script fingerprint-strings 192.168.1.100

Output Options

Different output formats:

bash
# Normal output
nmap -oN scan_results.txt 192.168.1.100

# XML output
nmap -oX scan_results.xml 192.168.1.100

# Grepable output
nmap -oG scan_results.gnmap 192.168.1.100

# All output formats
nmap -oA scan_results 192.168.1.100

# Script kiddie output
nmap -oS scan_results.skid 192.168.1.100

# Append to file
nmap --append-output -oN scan_results.txt 192.168.1.100

# Resume scan from file
nmap --resume scan_results.gnmap

# Verbose output
nmap -v 192.168.1.100
nmap -vv 192.168.1.100  # Extra verbose

# Debug output
nmap -d 192.168.1.100
nmap -dd 192.168.1.100  # Extra debug

# Packet trace
nmap --packet-trace 192.168.1.100

# Show only open ports
nmap --open 192.168.1.100

Advanced Features

Nmap Scripting Engine (NSE)

Using NSE scripts for advanced reconnaissance:

bash
# List available scripts
nmap --script-help all
ls /usr/share/nmap/scripts/

# Run default scripts
nmap -sC 192.168.1.100
nmap --script default 192.168.1.100

# Run specific script
nmap --script http-title 192.168.1.100

# Run multiple scripts
nmap --script "http-*" 192.168.1.100

# Run scripts by category
nmap --script vuln 192.168.1.100
nmap --script discovery 192.168.1.100
nmap --script auth 192.168.1.100
nmap --script brute 192.168.1.100
nmap --script exploit 192.168.1.100

# Script with arguments
nmap --script http-enum --script-args http-enum.basepath=/admin/ 192.168.1.100

# Multiple script arguments
nmap --script smb-enum-shares --script-args smbuser=admin,smbpass=password 192.168.1.100

# Script debugging
nmap --script http-title --script-trace 192.168.1.100

# Update script database
nmap --script-updatedb

# Common vulnerability scripts
nmap --script vuln 192.168.1.100
nmap --script "vuln and safe" 192.168.1.100

# Web application scripts
nmap --script "http-*" -p 80,443 192.168.1.100

# Database scripts
nmap --script "mysql-*" -p 3306 192.168.1.100
nmap --script "oracle-*" -p 1521 192.168.1.100

# SMB scripts
nmap --script "smb-*" -p 445 192.168.1.100

# SSH scripts
nmap --script "ssh-*" -p 22 192.168.1.100

Firewall Evasion

Techniques to evade firewalls and IDS:

bash
# Fragment packets
nmap -f 192.168.1.100
nmap -ff 192.168.1.100  # Use 8-byte fragments

# Specify MTU
nmap --mtu 24 192.168.1.100

# Use decoy addresses
nmap -D RND:10 192.168.1.100
nmap -D 192.168.1.5,192.168.1.6,ME 192.168.1.100

# Spoof source address
nmap -S 192.168.1.5 192.168.1.100

# Use specific interface
nmap -e eth0 192.168.1.100

# Spoof source port
nmap --source-port 53 192.168.1.100
nmap -g 53 192.168.1.100

# Randomize target order
nmap --randomize-hosts 192.168.1.0/24

# Add random data
nmap --data-length 25 192.168.1.100

# Use IPv6
nmap -6 2001:db8::1

# Idle scan (zombie host)
nmap -sI zombie_host:port target_host

# FTP bounce scan
nmap -b ftp_relay_host target_host

# Bad checksum
nmap --badsum 192.168.1.100

# Custom TCP flags
nmap --scanflags URGACKPSHRSTSYNFIN 192.168.1.100

Timing and Performance

Optimizing scan timing and performance:

bash
# Timing templates
nmap -T0 192.168.1.100  # Paranoid (very slow)
nmap -T1 192.168.1.100  # Sneaky (slow)
nmap -T2 192.168.1.100  # Polite (slower)
nmap -T3 192.168.1.100  # Normal (default)
nmap -T4 192.168.1.100  # Aggressive (faster)
nmap -T5 192.168.1.100  # Insane (very fast)

# Custom timing options
nmap --min-hostgroup 50 192.168.1.0/24
nmap --max-hostgroup 100 192.168.1.0/24

# Parallelism
nmap --min-parallelism 10 192.168.1.0/24
nmap --max-parallelism 100 192.168.1.0/24

# RTT timeout
nmap --min-rtt-timeout 100ms 192.168.1.100
nmap --max-rtt-timeout 2s 192.168.1.100
nmap --initial-rtt-timeout 500ms 192.168.1.100

# Retries
nmap --max-retries 3 192.168.1.100

# Scan delay
nmap --scan-delay 1s 192.168.1.100
nmap --max-scan-delay 10s 192.168.1.100

# Rate limiting
nmap --min-rate 100 192.168.1.0/24
nmap --max-rate 1000 192.168.1.0/24

# Host timeout
nmap --host-timeout 30m 192.168.1.0/24

# Defeat rate limiting
nmap --defeat-rst-ratelimit 192.168.1.100

IPv6 Scanning

Scanning IPv6 networks:

bash
# Basic IPv6 scan
nmap -6 2001:db8::1

# IPv6 ping scan
nmap -6 -sn 2001:db8::/64

# IPv6 port scan
nmap -6 -p 1-1000 2001:db8::1

# IPv6 service detection
nmap -6 -sV 2001:db8::1

# IPv6 with scripts
nmap -6 --script default 2001:db8::1

# IPv6 traceroute
nmap -6 --traceroute 2001:db8::1

# IPv6 OS detection
nmap -6 -O 2001:db8::1

# Scan IPv6 link-local
nmap -6 -e eth0 fe80::/64

# IPv6 multicast ping
nmap -6 -PE ff02::1%eth0

Automation Scripts

Comprehensive Network Scanner

python
#!/usr/bin/env python3
# Comprehensive network scanning with Nmap

import subprocess
import xml.etree.ElementTree as ET
import json
import csv
import argparse
import sys
import os
import time
from datetime import datetime
import threading
import queue

class NmapScanner:
    def __init__(self, nmap_path="nmap"):
        self.nmap_path = nmap_path
        self.results = {}
        self.scan_queue = queue.Queue()
        
    def verify_nmap_installation(self):
        """Verify Nmap installation"""
        try:
            result = subprocess.run([self.nmap_path, "--version"], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                version_line = result.stdout.split('\n')[0]
                print(f"Nmap version: {version_line}")
                return True
            else:
                print("Nmap not found or not working")
                return False
        except Exception as e:
            print(f"Error checking Nmap installation: {e}")
            return False
    
    def ping_sweep(self, target_range, output_file=None):
        """Perform ping sweep to discover live hosts"""
        print(f"Starting ping sweep for {target_range}")
        
        cmd = [self.nmap_path, "-sn", target_range]
        
        if output_file:
            cmd.extend(["-oX", output_file])
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            if result.returncode == 0:
                hosts = self.parse_ping_sweep_output(result.stdout)
                print(f"Discovered {len(hosts)} live hosts")
                return hosts
            else:
                print(f"Ping sweep failed: {result.stderr}")
                return []
        except subprocess.TimeoutExpired:
            print("Ping sweep timed out")
            return []
        except Exception as e:
            print(f"Error during ping sweep: {e}")
            return []
    
    def parse_ping_sweep_output(self, output):
        """Parse ping sweep output to extract live hosts"""
        hosts = []
        lines = output.split('\n')
        
        for line in lines:
            if "Nmap scan report for" in line:
                # Extract IP address
                parts = line.split()
                if len(parts) >= 5:
                    ip = parts[4]
                    if '(' in ip and ')' in ip:
                        ip = ip.strip('()')
                    hosts.append(ip)
        
        return hosts
    
    def port_scan(self, targets, ports="1-1000", scan_type="-sS", output_file=None):
        """Perform port scan on targets"""
        if isinstance(targets, list):
            targets = ",".join(targets)
        
        print(f"Starting port scan for {targets}")
        
        cmd = [self.nmap_path, scan_type, "-p", ports, targets]
        
        if output_file:
            cmd.extend(["-oX", output_file])
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
            
            if result.returncode == 0:
                scan_results = self.parse_port_scan_output(result.stdout)
                print(f"Port scan completed for {len(scan_results)} hosts")
                return scan_results
            else:
                print(f"Port scan failed: {result.stderr}")
                return {}
        except subprocess.TimeoutExpired:
            print("Port scan timed out")
            return {}
        except Exception as e:
            print(f"Error during port scan: {e}")
            return {}
    
    def parse_port_scan_output(self, output):
        """Parse port scan output"""
        results = {}
        current_host = None
        
        lines = output.split('\n')
        for line in lines:
            if "Nmap scan report for" in line:
                parts = line.split()
                if len(parts) >= 5:
                    current_host = parts[4]
                    if '(' in current_host and ')' in current_host:
                        current_host = current_host.strip('()')
                    results[current_host] = {'ports': []}
            elif "/tcp" in line or "/udp" in line:
                if current_host:
                    port_info = line.strip().split()
                    if len(port_info) >= 3:
                        port = port_info[0]
                        state = port_info[1]
                        service = port_info[2] if len(port_info) > 2 else "unknown"
                        
                        results[current_host]['ports'].append({
                            'port': port,
                            'state': state,
                            'service': service
                        })
        
        return results
    
    def service_detection(self, targets, ports=None, output_file=None):
        """Perform service and version detection"""
        if isinstance(targets, list):
            targets = ",".join(targets)
        
        print(f"Starting service detection for {targets}")
        
        cmd = [self.nmap_path, "-sV"]
        
        if ports:
            cmd.extend(["-p", ports])
        
        cmd.append(targets)
        
        if output_file:
            cmd.extend(["-oX", output_file])
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
            
            if result.returncode == 0:
                service_results = self.parse_service_detection_output(result.stdout)
                print(f"Service detection completed")
                return service_results
            else:
                print(f"Service detection failed: {result.stderr}")
                return {}
        except subprocess.TimeoutExpired:
            print("Service detection timed out")
            return {}
        except Exception as e:
            print(f"Error during service detection: {e}")
            return {}
    
    def parse_service_detection_output(self, output):
        """Parse service detection output"""
        results = {}
        current_host = None
        
        lines = output.split('\n')
        for line in lines:
            if "Nmap scan report for" in line:
                parts = line.split()
                if len(parts) >= 5:
                    current_host = parts[4]
                    if '(' in current_host and ')' in current_host:
                        current_host = current_host.strip('()')
                    results[current_host] = {'services': []}
            elif "/tcp" in line or "/udp" in line:
                if current_host and "open" in line:
                    service_info = line.strip().split(None, 2)
                    if len(service_info) >= 3:
                        port = service_info[0]
                        state = service_info[1]
                        service_detail = service_info[2]
                        
                        results[current_host]['services'].append({
                            'port': port,
                            'state': state,
                            'service': service_detail
                        })
        
        return results
    
    def vulnerability_scan(self, targets, script_category="vuln", output_file=None):
        """Perform vulnerability scanning using NSE scripts"""
        if isinstance(targets, list):
            targets = ",".join(targets)
        
        print(f"Starting vulnerability scan for {targets}")
        
        cmd = [self.nmap_path, "--script", script_category, targets]
        
        if output_file:
            cmd.extend(["-oX", output_file])
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=3600)
            
            if result.returncode == 0:
                vuln_results = self.parse_vulnerability_output(result.stdout)
                print(f"Vulnerability scan completed")
                return vuln_results
            else:
                print(f"Vulnerability scan failed: {result.stderr}")
                return {}
        except subprocess.TimeoutExpired:
            print("Vulnerability scan timed out")
            return {}
        except Exception as e:
            print(f"Error during vulnerability scan: {e}")
            return {}
    
    def parse_vulnerability_output(self, output):
        """Parse vulnerability scan output"""
        results = {}
        current_host = None
        current_script = None
        
        lines = output.split('\n')
        for line in lines:
            if "Nmap scan report for" in line:
                parts = line.split()
                if len(parts) >= 5:
                    current_host = parts[4]
                    if '(' in current_host and ')' in current_host:
                        current_host = current_host.strip('()')
                    results[current_host] = {'vulnerabilities': []}
            elif "|" in line and current_host:
                if line.strip().startswith("|_"):
                    # Script result
                    script_result = line.strip()[2:]
                    if current_script:
                        results[current_host]['vulnerabilities'].append({
                            'script': current_script,
                            'result': script_result
                        })
                elif line.strip().startswith("|"):
                    # Script name
                    current_script = line.strip()[1:].split(':')[0]
        
        return results
    
    def os_detection(self, targets, output_file=None):
        """Perform OS detection"""
        if isinstance(targets, list):
            targets = ",".join(targets)
        
        print(f"Starting OS detection for {targets}")
        
        cmd = [self.nmap_path, "-O", targets]
        
        if output_file:
            cmd.extend(["-oX", output_file])
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
            
            if result.returncode == 0:
                os_results = self.parse_os_detection_output(result.stdout)
                print(f"OS detection completed")
                return os_results
            else:
                print(f"OS detection failed: {result.stderr}")
                return {}
        except subprocess.TimeoutExpired:
            print("OS detection timed out")
            return {}
        except Exception as e:
            print(f"Error during OS detection: {e}")
            return {}
    
    def parse_os_detection_output(self, output):
        """Parse OS detection output"""
        results = {}
        current_host = None
        
        lines = output.split('\n')
        for line in lines:
            if "Nmap scan report for" in line:
                parts = line.split()
                if len(parts) >= 5:
                    current_host = parts[4]
                    if '(' in current_host and ')' in current_host:
                        current_host = current_host.strip('()')
                    results[current_host] = {'os_info': []}
            elif "Running:" in line and current_host:
                os_info = line.replace("Running:", "").strip()
                results[current_host]['os_info'].append(os_info)
            elif "OS details:" in line and current_host:
                os_details = line.replace("OS details:", "").strip()
                results[current_host]['os_info'].append(os_details)
        
        return results
    
    def comprehensive_scan(self, target_range, output_dir="/tmp/nmap_scan"):
        """Perform comprehensive network scan"""
        print("Starting comprehensive network scan...")
        
        # Create output directory
        os.makedirs(output_dir, exist_ok=True)
        
        scan_results = {
            'start_time': time.time(),
            'target_range': target_range,
            'live_hosts': [],
            'port_scan_results': {},
            'service_results': {},
            'vulnerability_results': {},
            'os_results': {}
        }
        
        # Step 1: Host discovery
        print("Step 1: Host discovery")
        ping_output = os.path.join(output_dir, "ping_sweep.xml")
        live_hosts = self.ping_sweep(target_range, ping_output)
        scan_results['live_hosts'] = live_hosts
        
        if not live_hosts:
            print("No live hosts found")
            return scan_results
        
        # Step 2: Port scanning
        print("Step 2: Port scanning")
        port_output = os.path.join(output_dir, "port_scan.xml")
        port_results = self.port_scan(live_hosts, "1-10000", "-sS", port_output)
        scan_results['port_scan_results'] = port_results
        
        # Step 3: Service detection
        print("Step 3: Service detection")
        service_output = os.path.join(output_dir, "service_detection.xml")
        service_results = self.service_detection(live_hosts, None, service_output)
        scan_results['service_results'] = service_results
        
        # Step 4: OS detection
        print("Step 4: OS detection")
        os_output = os.path.join(output_dir, "os_detection.xml")
        os_results = self.os_detection(live_hosts, os_output)
        scan_results['os_results'] = os_results
        
        # Step 5: Vulnerability scanning
        print("Step 5: Vulnerability scanning")
        vuln_output = os.path.join(output_dir, "vulnerability_scan.xml")
        vuln_results = self.vulnerability_scan(live_hosts, "vuln", vuln_output)
        scan_results['vulnerability_results'] = vuln_results
        
        scan_results['end_time'] = time.time()
        scan_results['duration'] = scan_results['end_time'] - scan_results['start_time']
        
        # Generate reports
        self.generate_json_report(scan_results, os.path.join(output_dir, "scan_results.json"))
        self.generate_csv_report(scan_results, os.path.join(output_dir, "scan_results.csv"))
        self.generate_html_report(scan_results, os.path.join(output_dir, "scan_report.html"))
        
        print(f"Comprehensive scan completed in {scan_results['duration']:.2f} seconds")
        print(f"Results saved to: {output_dir}")
        
        return scan_results
    
    def generate_json_report(self, results, output_file):
        """Generate JSON report"""
        with open(output_file, 'w') as f:
            json.dump(results, f, indent=2, default=str)
        print(f"JSON report generated: {output_file}")
    
    def generate_csv_report(self, results, output_file):
        """Generate CSV report"""
        with open(output_file, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['Host', 'Port', 'State', 'Service', 'Version', 'OS', 'Vulnerabilities'])
            
            for host in results['live_hosts']:
                # Port information
                port_info = results['port_scan_results'].get(host, {}).get('ports', [])
                service_info = results['service_results'].get(host, {}).get('services', [])
                os_info = results['os_results'].get(host, {}).get('os_info', [])
                vuln_info = results['vulnerability_results'].get(host, {}).get('vulnerabilities', [])
                
                if port_info:
                    for port in port_info:
                        # Find corresponding service info
                        service_detail = ""
                        for service in service_info:
                            if service['port'] == port['port']:
                                service_detail = service['service']
                                break
                        
                        writer.writerow([
                            host,
                            port['port'],
                            port['state'],
                            port['service'],
                            service_detail,
                            '; '.join(os_info),
                            '; '.join([v['result'] for v in vuln_info])
                        ])
                else:
                    writer.writerow([
                        host,
                        '',
                        '',
                        '',
                        '',
                        '; '.join(os_info),
                        '; '.join([v['result'] for v in vuln_info])
                    ])
        
        print(f"CSV report generated: {output_file}")
    
    def generate_html_report(self, results, output_file):
        """Generate HTML report"""
        html_content = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Nmap Comprehensive Scan Report</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; }}
        .section {{ margin: 20px 0; padding: 15px; border: 1px solid #ddd; }}
        .critical {{ color: red; font-weight: bold; }}
        .warning {{ color: orange; font-weight: bold; }}
        .info {{ color: blue; }}
        .success {{ color: green; font-weight: bold; }}
        table {{ border-collapse: collapse; width: 100%; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
        pre {{ background: #f5f5f5; padding: 10px; overflow-x: auto; }}
    </style>
</head>
<body>
    <h1>Nmap Comprehensive Scan Report</h1>
    <p>Generated: {datetime.now().isoformat()}</p>
    <p>Target Range: {results['target_range']}</p>
    <p>Scan Duration: {results['duration']:.2f} seconds</p>
    
    <div class="section">
        <h2>Executive Summary</h2>
        <ul>
            <li>Live Hosts Discovered: {len(results['live_hosts'])}</li>
            <li>Hosts with Open Ports: {len(results['port_scan_results'])}</li>
            <li>Services Identified: {sum(len(host.get('services', [])) for host in results['service_results'].values())}</li>
            <li>Vulnerabilities Found: {sum(len(host.get('vulnerabilities', [])) for host in results['vulnerability_results'].values())}</li>
        </ul>
    </div>
    
    <div class="section">
        <h2>Live Hosts</h2>
        <table>
            <tr><th>IP Address</th><th>Open Ports</th><th>Operating System</th></tr>
"""
        
        for host in results['live_hosts']:
            port_count = len(results['port_scan_results'].get(host, {}).get('ports', []))
            os_info = '; '.join(results['os_results'].get(host, {}).get('os_info', ['Unknown']))
            
            html_content += f"""
            <tr>
                <td>{host}</td>
                <td>{port_count}</td>
                <td>{os_info}</td>
            </tr>"""
        
        html_content += """
        </table>
    </div>
    
    <div class="section">
        <h2 class="critical">Vulnerabilities</h2>
        <table>
            <tr><th>Host</th><th>Script</th><th>Result</th></tr>
"""
        
        for host, data in results['vulnerability_results'].items():
            for vuln in data.get('vulnerabilities', []):
                html_content += f"""
                <tr>
                    <td>{host}</td>
                    <td>{vuln['script']}</td>
                    <td>{vuln['result']}</td>
                </tr>"""
        
        html_content += """
        </table>
    </div>
    
    <div class="section">
        <h2>Detailed Host Information</h2>
"""
        
        for host in results['live_hosts']:
            html_content += f"""
            <h3>{host}</h3>
            <h4>Open Ports</h4>
            <table>
                <tr><th>Port</th><th>State</th><th>Service</th><th>Version</th></tr>
"""
            
            ports = results['port_scan_results'].get(host, {}).get('ports', [])
            services = results['service_results'].get(host, {}).get('services', [])
            
            for port in ports:
                service_detail = ""
                for service in services:
                    if service['port'] == port['port']:
                        service_detail = service['service']
                        break
                
                html_content += f"""
                <tr>
                    <td>{port['port']}</td>
                    <td>{port['state']}</td>
                    <td>{port['service']}</td>
                    <td>{service_detail}</td>
                </tr>"""
            
            html_content += "</table>"
        
        html_content += """
    </div>
</body>
</html>
"""
        
        with open(output_file, 'w') as f:
            f.write(html_content)
        
        print(f"HTML report generated: {output_file}")

def main():
    parser = argparse.ArgumentParser(description='Comprehensive Nmap Scanner')
    parser.add_argument('--target', required=True, help='Target range (e.g., 192.168.1.0/24)')
    parser.add_argument('--output', default='/tmp/nmap_scan', help='Output directory')
    parser.add_argument('--nmap-path', default='nmap', help='Path to Nmap executable')
    
    args = parser.parse_args()
    
    # Initialize scanner
    scanner = NmapScanner(args.nmap_path)
    
    # Verify installation
    if not scanner.verify_nmap_installation():
        print("Nmap not properly installed or configured")
        sys.exit(1)
    
    # Run comprehensive scan
    results = scanner.comprehensive_scan(args.target, args.output)
    
    if results:
        print("Comprehensive scan completed successfully")
    else:
        print("Comprehensive scan failed")
        sys.exit(1)

if __name__ == "__main__":
    main()

Integration Examples

SIEM Integration

bash
# Splunk integration script
#!/bin/bash

# Nmap to Splunk integration
SPLUNK_INDEX="network_security"
SPLUNK_HOST="splunk.company.com"
SPLUNK_PORT="8088"
SPLUNK_TOKEN="your-hec-token"

# Run Nmap scan
nmap -sS -sV -O --script vuln -oX scan_results.xml 192.168.1.0/24

# Convert XML to JSON for Splunk
python3 << 'EOF'
import xml.etree.ElementTree as ET
import json
import requests
from datetime import datetime

# Parse Nmap XML
tree = ET.parse('scan_results.xml')
root = tree.getroot()

events = []

for host in root.findall('host'):
    host_ip = host.find('address').get('addr')
    
    # Host information
    event = {
        'timestamp': datetime.now().isoformat(),
        'source': 'nmap',
        'host': host_ip,
        'event_type': 'host_discovery'
    }
    
    # OS information
    os_elem = host.find('os')
    if os_elem is not None:
        osmatch = os_elem.find('osmatch')
        if osmatch is not None:
            event['os'] = osmatch.get('name')
            event['accuracy'] = osmatch.get('accuracy')
    
    events.append(event)
    
    # Port information
    ports = host.find('ports')
    if ports is not None:
        for port in ports.findall('port'):
            port_event = {
                'timestamp': datetime.now().isoformat(),
                'source': 'nmap',
                'host': host_ip,
                'event_type': 'port_scan',
                'port': port.get('portid'),
                'protocol': port.get('protocol'),
                'state': port.find('state').get('state')
            }
            
            service = port.find('service')
            if service is not None:
                port_event['service'] = service.get('name')
                port_event['version'] = service.get('version')
                port_event['product'] = service.get('product')
            
            events.append(port_event)
    
    # Script results (vulnerabilities)
    hostscript = host.find('hostscript')
    if hostscript is not None:
        for script in hostscript.findall('script'):
            vuln_event = {
                'timestamp': datetime.now().isoformat(),
                'source': 'nmap',
                'host': host_ip,
                'event_type': 'vulnerability',
                'script': script.get('id'),
                'output': script.get('output')
            }
            events.append(vuln_event)

# Send to Splunk HEC
headers = {
    'Authorization': f'Splunk {SPLUNK_TOKEN}',
    'Content-Type': 'application/json'
}

for event in events:
    payload = {
        'index': SPLUNK_INDEX,
        'event': event
    }
    
    response = requests.post(
        f'https://{SPLUNK_HOST}:{SPLUNK_PORT}/services/collector',
        headers=headers,
        json=payload,
        verify=False
    )
    
    if response.status_code != 200:
        print(f'Failed to send event: {response.text}')

print(f'Sent {len(events)} events to Splunk')
EOF

Troubleshooting

Common Issues

Permission Issues:

bash
# Run as root for SYN scans
sudo nmap -sS 192.168.1.100

# Use TCP connect scan without root
nmap -sT 192.168.1.100

# Check capabilities
getcap /usr/bin/nmap

# Set capabilities (alternative to root)
sudo setcap cap_net_raw,cap_net_admin,cap_net_bind_service+eip /usr/bin/nmap

Firewall Issues:

bash
# Test connectivity
ping 192.168.1.100
telnet 192.168.1.100 80

# Use different scan techniques
nmap -sA 192.168.1.100  # ACK scan
nmap -sF 192.168.1.100  # FIN scan
nmap -sN 192.168.1.100  # NULL scan

# Fragment packets
nmap -f 192.168.1.100

# Use decoys
nmap -D RND:10 192.168.1.100

Performance Issues:

bash
# Reduce timing
nmap -T2 192.168.1.0/24

# Limit parallelism
nmap --max-parallelism 10 192.168.1.0/24

# Increase timeouts
nmap --host-timeout 30m 192.168.1.0/24

# Scan smaller ranges
nmap 192.168.1.1-50

Script Debugging

Debugging NSE scripts:

bash
# Enable script tracing
nmap --script http-title --script-trace 192.168.1.100

# Debug specific script
nmap --script vuln --script-trace -d 192.168.1.100

# Test script syntax
nmap --script-help script-name

# Update script database
nmap --script-updatedb

# List script categories
nmap --script-help all | grep Categories

# Custom script debugging
lua /usr/share/nmap/scripts/script-name.nse

Security Considerations

Operational Security

Legal and Ethical Usage:

  • Only scan networks you own or have explicit permission to test
  • Understand legal requirements for network scanning in your jurisdiction
  • Implement proper authorization and documentation procedures
  • Respect scope limitations and rules of engagement
  • Be aware of potential service disruption from aggressive scans

Stealth Considerations:

  • Use appropriate timing templates to avoid detection
  • Implement source IP spoofing and decoy techniques when necessary
  • Fragment packets to evade simple packet filters
  • Randomize scan order and timing to avoid patterns
  • Monitor target systems for signs of detection or blocking

Defensive Considerations

Detection and Prevention:

  • Monitor for Nmap signatures and scanning patterns
  • Implement network intrusion detection systems
  • Deploy honeypots to detect reconnaissance activities
  • Log and analyze network connection attempts
  • Implement rate limiting and connection throttling

References

  1. Nmap Official Documentation
  2. Nmap Network Scanning Book
  3. NSE Script Documentation
  4. Nmap GitHub Repository
  5. Network Security Assessment Guidelines