杰瑞科技汇

python nmap product

Of course! When you talk about a "Python nmap product," you're almost certainly referring to using a Python library to control and automate the Nmap security scanner. This is a very common and powerful practice for network administrators, security professionals, and developers.

python nmap product-图1
(图片来源网络,侵删)

Here's a complete guide covering the most popular Python library, python-nmap, including installation, usage, and advanced examples.


The Core Idea: Bridging Python and Nmap

Nmap is an incredibly powerful command-line tool. However, its output can be difficult to parse, and it's not designed for easy integration into larger applications. Python, on the other hand, excels at data manipulation, web development, and automation.

A "Python nmap product" uses a Python library to:

  1. Execute Nmap: Run Nmap scans directly from your Python script.
  2. Parse Output: Take the text or XML output from Nmap and convert it into structured Python objects (like dictionaries and lists).
  3. Automate & Integrate: Use the parsed data to make decisions, generate reports, feed data into a database, or create a web interface.

The most widely used library for this is python-nmap.

python nmap product-图2
(图片来源网络,侵删)

Installation

First, you need to have Nmap installed on your system. python-nmap is just a wrapper; it doesn't contain Nmap itself.

Install Nmap

On Debian/Ubuntu:

sudo apt-get update
sudo apt-get install nmap

On macOS (using Homebrew):

brew install nmap

On Windows (using Chocolatey):

python nmap product-图3
(图片来源网络,侵删)
choco install nmap

Or download the installer directly from the Nmap official website.

Install the Python Library

Once Nmap is installed, you can install the Python library using pip:

pip install python-nmap

Basic Usage of python-nmap

The library has two main classes:

  • PortScanner(): The most common class. It's used to run new scans and parse the results.
  • PortScannerAsync(): For running scans in a non-blocking way (in the background), which is useful for GUI applications or web servers.

Let's focus on PortScanner().

Example 1: Perform a Simple Scan and Iterate

This script will scan a single host and print out the open ports and their services.

import nmap
# Create a PortScanner object
nm = nmap.PortScanner()
# Define the target to scan
target = "scanme.nmap.org" # A safe, dedicated test host
# Perform the scan
# Arguments are: <target>, <port range>, <nmap options>
# -sS: TCP SYN scan (requires root/admin privileges)
# -O: Enable OS detection
# -sV: Enable version detection
nm.scan(target, arguments='-sS -O -sV')
# --- Process and Print the Results ---
print(f"Command line: {nm.command_line()}")
print(f"Scan information: {nm.scaninfo()}")
# Check if the host was found
if target in nm.all_hosts():
    print(f"\n--- Host: {target} ({nm[target].hostname()}) ---")
    print(f"State: {nm[target].state()}")
    # Iterate over all protocols found (e.g., 'tcp', 'udp')
    for proto in nm[target].all_protocols():
        print(f"\nProtocol: {proto}")
        # Get all ports for this protocol
        ports = nm[target][proto].keys()
        # Sort the ports for cleaner output
        for port in sorted(ports):
            print(f"  Port: {port}\tState: {nm[target][proto][port]['state']}\tService: {nm[target][proto][port]['name']}")
else:
    print(f"Host {target} not found in the scan results.")

Example 2: Parse a Pre-existing Nmap XML File

A common use case is to analyze the output of a scan that was already run. The PortScanner can parse an Nmap XML file directly.

Let's say you have a file named scan_results.xml from a previous Nmap run (nmap -oX scan_results.xml 192.168.1.1).

import nmap
# Create a PortScanner object
nm = nmap.PortScanner()
# The path to your Nmap XML output file
xml_file = "scan_results.xml"
# Parse the XML file
nm.scan(hosts='localhost', arguments=f'-iL {xml_file}')
# The rest of the parsing code is the same as in Example 1
for host in nm.all_hosts():
    print(f"\n--- Host: {host} ---")
    for proto in nm[host].all_protocols():
        print(f"Protocol: {proto}")
        ports = sorted(nm[host][proto].keys())
        for port in ports:
            port_info = nm[host][proto][port]
            print(f"  Port: {port}\tState: {port_info['state']}\tProduct: {port_info.get('product', 'N/A')}\tVersion: {port_info.get('version', 'N/A')}")

Building a "Product" - Practical Examples

Here’s how you can use these building blocks to create more advanced tools.

Example 3: Automated Vulnerability Scan Report

This script scans a network, identifies web servers (ports 80, 443), and generates a simple report. This could be the basis for a dashboard or a notification system.

import nmap
import json
def generate_vulnerability_report(network_range):
    """
    Scans a network range for open ports and generates a JSON report.
    """
    nm = nmap.PortScanner()
    report = {"scan_summary": [], "findings": []}
    print(f"[*] Scanning {network_range}...")
    nm.scan(hosts=network_range, arguments='-sS')
    for host in nm.all_hosts():
        host_info = {
            "host": host,
            "state": nm[host].state(),
            "os": nm[host].get('osmatch', [{'name': 'Unknown'}])[0]['name']
        }
        report["scan_summary"].append(host_info)
        for proto in nm[host].all_protocols():
            ports = nm[host][proto].keys()
            for port in sorted(ports):
                port_info = nm[host][proto][port]
                # --- Custom Logic for "Vulnerabilities" ---
                finding = None
                if port_info['state'] == 'open':
                    if port in [80, 8080, 8000]:
                        finding = f"HTTP server open on port {port}"
                    elif port in [443, 8443]:
                        finding = f"HTTPS server open on port {port}"
                    elif port == 22:
                        finding = f"SSH server open on port {port} - Verify access policies."
                    elif port == 3389:
                        finding = f"RDP service open on port {port} - Check for weak credentials."
                if finding:
                    report["findings"].append({
                        "host": host,
                        "port": port,
                        "service": port_info.get('name', 'unknown'),
                        "finding": finding
                    })
    return report
# --- Main Execution ---
if __name__ == "__main__":
    # Scan your local /24 network (change as needed)
    network_to_scan = "192.168.1.0/24"
    vulnerability_report = generate_vulnerability_report(network_to_scan)
    # Print a summary to the console
    print("\n--- Scan Report ---")
    print(f"Hosts scanned: {len(vulnerability_report['scan_summary'])}")
    print(f"Potential findings: {len(vulnerability_report['findings'])}")
    for finding in vulnerability_report['findings']:
        print(f"[!] {finding['host']}:{finding['port']} ({finding['service']}) - {finding['finding']}")
    # Save the full report to a JSON file
    with open("vulnerability_report.json", "w") as f:
        json.dump(vulnerability_report, f, indent=4)
    print("\n[*] Full report saved to vulnerability_report.json")

Example 4: Creating a Simple Web Dashboard with Flask

This is a more advanced "product" that uses Flask to serve a web page displaying the scan results.

Prerequisites: pip install flask

app.py

from flask import Flask, render_template_string
import nmap
import json
app = Flask(__name__)
# A simple HTML template for our dashboard
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>Nmap Scan Dashboard</title>
    <style>body {{ font-family: sans-serif; }} .finding {{ color: red; }}</style>
</head>
<body>
    <h1>Nmap Scan Dashboard</h1>
    <h2>Scan Results for {{ target }}</h2>
    <table border="1">
        <tr><th>Host</th><th>Port</th><th>State</th><th>Service</th><th>Version</th></tr>
        {% for result in results %}
        <tr class="{% if result.state == 'open' %}finding{% endif %}">
            <td>{{ result.host }}</td>
            <td>{{ result.port }}</td>
            <td>{{ result.state }}</td>
            <td>{{ result.service }}</td>
            <td>{{ result.version }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
"""
@app.route('/')
def scan_dashboard():
    # Define the target to scan
    target = "127.0.0.1" # Scan localhost for safety
    # Perform the scan
    nm = nmap.PortScanner()
    nm.scan(target, arguments='-sS')
    # Prepare data for the template
    results_for_template = []
    for host in nm.all_hosts():
        for proto in nm[host].all_protocols():
            for port in nm[host][proto].keys():
                port_info = nm[host][proto][port]
                results_for_template.append({
                    'host': host,
                    'port': port,
                    'state': port_info['state'],
                    'service': port_info.get('name', 'N/A'),
                    'version': port_info.get('version', 'N/A')
                })
    return render_template_string(HTML_TEMPLATE, target=target, results=results_for_template)
if __name__ == '__main__':
    # Run the app on http://127.0.0.1:5000
    app.run(debug=True)

To run this, simply execute python app.py and open your web browser to http://127.0.0.1:5000.


Important Considerations

  • Permissions: Some Nmap scan types (like SYN scans -sS) require root or Administrator privileges. Your Python script will also need to be run with these elevated permissions to execute them.
  • Performance: Scanning large networks can be slow and resource-intensive. Be mindful of the target and the scan arguments you use.
  • Legality and Ethics: Only scan networks and systems that you own or have explicit, written permission to scan. Unauthorized scanning is illegal in many jurisdictions and can be considered a hostile act. The test host scanme.nmap.org is provided by the Nmap project specifically for safe practice.
  • Alternatives: While python-nmap is the most popular, other libraries exist, such as python-libnmap, which offers a slightly different API but achieves the same goal.
分享:
扫描分享到社交APP
上一篇
下一篇