NMAP (Network Mapper) is an open source tool for network exploration and security auditing. It can discover hosts and services on a computer network, thus building a “map” of the network.
When it comes to running NMAP from Python, there is a third-party library available that enables you to do just that – python-nmap. python-nmap is a Python library which enables NMAP script execution and parsing its output programmatically from Python (Github, python-nmap: https://github.com/savon-noir/python-nmap).
Let’s dive in on how you can install and use this library to run NMAP from Python. The first thing you need to do is to install python-nmap. You can do this via pip, which is a package manager for Python. Open your terminal and type in the following command: `pip install python-nmap`.
After successfully installing python-nmap, you can import it into your Python script and use it to run NMAP. Here’s a basic example:
```
import nmap
nm = nmap.PortScanner()
In the above example, we first import the nmap module, then create a new PortScanner object. After that, we call the scan method on this object, passing the host and the range of ports we want to scan as arguments (The Python Standard Library, nmap – Port scanning: https://docs.python.org/3/library/nmap.html).
You can even leverage NMAP’s scripting feature right from python-nmap. For example, you can execute the “banner” script to grab the banner information of a service:
```
import nmap
nm = nmap.PortScanner()
nm.scan(‘127.0.0.1’, arguments=’-p 22 —script banner’)
```
In this way, you can integrate and leverage the full power of NMAP in your Python programs. A word of caution: as with NMAP, you should only use python-nmap responsibly and on networks that you have permission to scan. Unauthorized scanning is illegal and can get you into legal trouble. (NMAP, Legal Issues: https://nmap.org/book/legal-issues.html).