python-nmap: Nmap Integration with Python
python-nmap is a Python library that provides an easy-to-use interface to Nmap, the powerful network discovery and security auditing tool. It allows you to programmatically launch Nmap scans, parse its output, and integrate network scanning capabilities directly into your Python scripts and applications. This is incredibly useful for automating reconnaissance, building custom network tools, or creating dynamic security assessments.
1. Prerequisites
Before using python-nmap, you must have Nmap itself installed on your system. python-nmap is just a wrapper around the Nmap executable.
You can install Nmap on most Linux distributions using your package manager (e.g., sudo apt install nmap on Debian/Ubuntu, sudo yum install nmap on CentOS/RHEL).
2. Installation of python-nmap
Install the Python library using pip:
pip install python-nmap3. Basic Usage
The core of python-nmap involves creating a PortScanner object and then calling its scan() method with the desired Nmap arguments.
import nmap
# Initialize the PortScanner
nm = nmap.PortScanner()
# Perform a scan
# hosts: The target host(s) or IP range
# arguments: Any valid Nmap command-line arguments (e.g., -Pn, -p, -sS, -sV)
nm.scan(hosts='192.168.0.100', arguments='-Pn -p 22-80,443 -sV -O')
# Print the Nmap command that was executed (useful for debugging)
print(f"Executed Nmap command: {nm.command_line()}")
# Iterate through all scanned hosts
for host in nm.all_hosts():
print(f"----------------------------------------------------")
print(f"Host : {host} ({nm[host].hostname()})")
print(f"State : {nm[host].state()}")
# Iterate through scanned TCP ports
if 'tcp' in nm[host]:
print("TCP Ports:")
for proto in nm[host].all_protocols():
lport = nm[host][proto].keys()
for port in lport:
print(f"Port : {port}\tState : {nm[host][proto][port]['state']}\tName : {nm[host][proto][port]['name']}")
print(f"\tProduct : {nm[host][proto][port]['product']}")
print(f"\tVersion : {nm[host][proto][port]['version']}")
print(f"\tExtra : {nm[host][proto][port]['extrainfo']}")
# Get OS information (if -O was used)
if 'osmatch' in nm[host]:
for osmatch in nm[host]['osmatch']:
print(f"OS Match : {osmatch['name']} (Accuracy: {osmatch['accuracy']}%)")
print(f"----------------------------------------------------")Explanation of Key Methods:
nmap.PortScanner(): Creates a new instance of the Nmap scanner.nm.scan(hosts='...', arguments='...'): Executes an Nmap scan.hosts: A string specifying the target(s) (e.g.,'192.168.1.1','192.168.1.0/24','scanme.nmap.org').arguments: A string containing the Nmap command-line flags you would normally use (e.g.,'-p 22-100 -sS -sV').
nm.command_line(): Returns the exact Nmap command that was executed by the library.nm.all_hosts(): Returns a list of all IP addresses that were scanned.nm[host].hostname(): Gets the hostname of a specific host.nm[host].state(): Gets the overall state of the host (e.g.,'up','down').nm[host].all_protocols(): Returns a list of protocols (e.g.,['tcp', 'udp']) found for a host.nm[host][proto].keys(): Returns a list of port numbers for a given protocol.nm[host][proto][port]['state']: Gets the state of a specific port (e.g.,'open','closed','filtered').nm[host][proto][port]['product'],['version'], etc.: Accesses detailed service information if service detection (-sV) was enabled.nm[host]['osmatch']: Accesses a list of possible OS matches if OS detection (-O) was enabled.
This library provides a programmatic and structured way to interact with Nmap’s powerful scanning capabilities, allowing for flexible and automated network insights.