python-nmap

0.7.1 · active · verified Thu Apr 16

python-nmap is a Python library that provides a convenient interface for interacting with the Nmap security scanner. It allows Python scripts to build and execute Nmap scans, parse scan results, and automate network discovery and vulnerability assessment tasks. The library is currently at version 0.7.1 and has an irregular release cadence, with updates addressing bugs and improving compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform a basic port scan on a target IP address and then print the host information, state, and details for all discovered open ports and their services. It includes basic error handling for common Nmap-related issues.

import nmap
import os

# Instantiate the PortScanner
nm = nmap.PortScanner()

# Define target and ports
target_host = os.environ.get('SCAN_TARGET_IP', '127.0.0.1')
scan_ports = os.environ.get('SCAN_PORTS', '22-443')

try:
    # Perform a scan
    nm.scan(target_host, scan_ports)

    # Iterate through scanned hosts
    for host in nm.all_hosts():
        print(f'Host : {host} ({nm[host].hostname()})')
        print(f'State : {nm[host].state()}')
        for proto in nm[host].all_protocols():
            print('----------')
            print(f'Protocol : {proto}')

            lport = nm[host][proto].keys()
            for port in lport:
                print(f'port : {port}\tstate : {nm[host][proto][port]['state']}')
except nmap.nmap.PortScannerError as e:
    print(f"Error during scan: {e}")
    print("Please ensure Nmap is installed and in your system's PATH.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →