python3-nmap
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
-
FileNotFoundError: [Errno 2] No such file or directory: 'nmap program was not found in path'
cause The Nmap binary is not installed on your system or is not located in a directory listed in your system's PATH environment variable.fixInstall the Nmap command-line tool for your operating system (e.g., `sudo apt install nmap` on Debian/Ubuntu, `brew install nmap` on macOS, or download from nmap.org for Windows). Ensure the Nmap executable's directory is in your system's PATH. -
('Nmap not found', <class 'nmap.nmap.PortScannerError'>)cause Similar to the `FileNotFoundError`, this error indicates that the `python-nmap` library (which `python3-nmap` is often confused with) cannot locate the Nmap binary.fixVerify that the Nmap binary is installed and its location is in your system's PATH. For Windows users, you might need to manually add the Nmap installation directory to your environment variables. -
AttributeError: module 'nmap' has no attribute 'PortScanner'
cause You have likely installed `python3-nmap` but are attempting to use the `PortScanner` class from the older `python-nmap` library (which uses `import nmap`). `python3-nmap`'s primary class is `nmap3.Nmap`.fixChange your import statement from `import nmap` to `from nmap3 import Nmap` and adapt your code to use the `nmap3` API. If you specifically need the `PortScanner` class, you might need to uninstall `python3-nmap` and install `python-nmap` instead (`pip install python-nmap`). -
ModuleNotFoundError: No module named 'nmap3'
cause The `python3-nmap` library, which provides the `nmap3` module, is not installed in your current Python environment. This could be due to a missed installation, a virtual environment issue, or installing the wrong library (e.g., `python-nmap`).fixEnsure `python3-nmap` is installed in your active Python environment: `pip install python3-nmap`. If using a virtual environment, activate it before installing. Verify with `pip show python3-nmap`.
Warnings
- breaking The `python3-nmap` library is a wrapper around the Nmap command-line tool. You MUST install the Nmap binary (e.g., `sudo apt install nmap` on Linux) separately on your system for `python3-nmap` to function. Failure to do so will result in `Nmap program was not found in path` errors.
- gotcha There are two popular Python Nmap wrapper libraries: `python-nmap` and `python3-nmap`. They have different APIs and import paths (`import nmap` vs. `from nmap3 import Nmap`). Installing `python3-nmap` but using `import nmap` will lead to `AttributeError: module 'nmap' has no attribute 'PortScanner'`.
- gotcha Some Nmap scan types, particularly OS detection (`nmap_os_detection`) and certain advanced techniques, require root or administrator privileges to execute successfully. Running your Python script without these privileges will result in failed scans or incomplete results.
- deprecated The older `python-nmap` library, which `python3-nmap` is a successor to, underwent significant API changes. For instance, `PortScannerAsync` was removed and `PortScannerYield` was renamed to `iterscan` in `python-nmap` version 0.7.0. While `python3-nmap` is a separate project, be aware that migrating from very old `python-nmap` codebases might involve significant refactoring.
Install
-
pip install python3-nmap -
sudo apt install nmap # On Debian/Ubuntu brew install nmap # On macOS # Download and install from nmap.org for Windows
Imports
- Nmap
import nmap
from nmap3 import Nmap
Quickstart
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")