python3-nmap

1.9.1 · active · verified Thu Apr 16

Python3-nmap converts Nmap commands into python3 methods making it very easy to use nmap in any of your python pentesting projects. It provides a Python 3 interface to the Nmap port scanner, enabling manipulation of scan results and automation of scanning tasks and reports. The library is actively maintained, with the latest stable release being 1.9.1.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes the `nmap3.Nmap` class and performs a top ports scan on a specified target. It then prints the host and open port information. Remember to have the Nmap binary installed on your system.

import nmap3

def run_nmap_scan(target_host):
    try:
        # Initialize nmap3
        nmap = nmap3.Nmap()

        # Perform a top ports scan (example: scanme.nmap.org is a safe target)
        print(f"Scanning top ports on {target_host}...")
        results = nmap.scan_top_ports(target_host)

        if results:
            print("Scan results:")
            for host, host_data in results.items():
                if host == 'runtime': continue # Skip runtime metadata
                print(f"  Host: {host}")
                for port_entry in host_data['ports']:
                    port_id = port_entry.get('portid')
                    state = port_entry.get('state')
                    service = port_entry.get('service', {}).get('name')
                    product = port_entry.get('service', {}).get('product')
                    version = port_entry.get('service', {}).get('version')
                    
                    port_info = f"    Port: {port_id}/{port_entry.get('protocol')} State: {state}"
                    if service: port_info += f" Service: {service}"
                    if product: port_info += f" Product: {product}"
                    if version: port_info += f" Version: {version}"
                    print(port_info)
        else:
            print("No results found or host is down.")

    except nmap3.exceptions.NmapCommandError as e:
        print(f"Nmap command error: {e}. Ensure Nmap is installed and in your PATH.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

# Replace 'scanme.nmap.org' with your target. 
# DO NOT scan hosts without explicit permission.
run_nmap_scan("scanme.nmap.org")

view raw JSON →