python-nmap
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
-
('Nmap not found', <class 'nmap.nmap.PortScannerError'>)cause The Nmap executable (the system tool) is either not installed or not found in the system's PATH environment variable.fixInstall the Nmap security scanner on your operating system. For Linux (Debian/Ubuntu), use `sudo apt install nmap`. For Windows or macOS, download the installer from nmap.org. Verify Nmap is installed by running `nmap --version` in your terminal. Ensure its installation directory is in your system's PATH. -
AttributeError: module 'nmap' has no attribute 'PortScanner'
cause You have a Python file named `nmap.py` in your project directory or Python's import path, which conflicts with the installed `python-nmap` library. Python imports your local file instead of the library.fixRename your Python script file to something unique (e.g., `my_scanner.py`). If you still encounter the error, delete any `.pyc` files or `__pycache__` directories in your project. -
OSError: [Errno 2] No such file or directory
cause This error often occurs when the `nmap` executable itself cannot be found or executed by the Python script, typically due to it not being in the system's PATH.fixEnsure the Nmap system tool is correctly installed and its executable is accessible in your system's PATH. On some systems, you might need to provide the full path to the nmap executable when instantiating PortScanner: `nm = nmap.PortScanner('/usr/local/bin/nmap')` (adjust path as needed).
Warnings
- breaking Nmap executable (the system tool) must be installed and in your system's PATH. This Python library is a wrapper and will not work if Nmap is not found. This is the most common reason for errors.
- gotcha Naming your Python script `nmap.py` will cause an `AttributeError: module 'nmap' has no attribute 'PortScanner'`. This is because Python will try to import your own script instead of the installed `python-nmap` library.
- deprecated Older versions of `python-nmap` included `PortScannerAsync` for asynchronous scanning. This class was removed, and asynchronous operations are now typically handled via the `iterscan` method within the `PortScanner` class, or by using Python's `asyncio` with `subprocess` for more fine-grained control.
Install
-
pip install python-nmap
Imports
- PortScanner
from nmap import nmap
import nmap nm = nmap.PortScanner()
Quickstart
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}")