Python and Nmap InfosecAddicts

Python and Nmap

Blog / frontpge

Python and Nmap

Python is one of the best programming languages and is widely used by hackers; in this post, we will look at how we can use NMAP from python.

The first thing we are going to do is install Nmap in our operating system; if you are starting in the world of cybersecurity, remember that you should use Linux because everything is more accessible.

sudo apt-get install nmap

Now, we install the python module that we will use, with the following command:

pip install python-nmap

Did you see how easy it is? With two lines of command, we are ready to go.

I remind you that to work with python, you must always have a virtual environment, where you will install all the modules that you will use, and in this way, you separate your project from others.

ptyhon -m venv <name of your virtual environment>

My environment is called env3 as seen in the following image, you can create all the environments you need.

After having everything installed and our active virtual environment, then, we will start using each of the methods that the nmap module has for us.


We pass two arguments to the scan method: the IP or the host, and the range of ports to scan.

import nmap
# initialize the port scanner
nmScan = nmap.PortScanner()
# scan localhost for ports in range 21-443
nmScan.scan(‘′, ’21-443’)

Method result

get command line used for the scan : nmap -oX – -p 22-443


get nmap scan informations {‘tcp’: {‘services’: ’22-443′, ‘method’: ‘connect’}}


get all hosts that were scanned


get hostname for host


get state of host (up|down|unknown|skipped)


The all_protocols () method, returns the protocol for the network that is being scanned.


The keys () method, returns all available active ports within an specified range.


is there any information for port 22/tcp on host


I hope this helps you to automate your nmap tasks, and if you know about software development, I invite you to create a rest service with Django rest-framework, so, you can consume all the nmap methods from the frontend with React, Vue or Angular.

Every time you investigate more about python, you will realize that it is so helpful for hackers as a tool, even though, there are other alternatives like ruby, python still the most popular due to the large number of people that use it in our field

YouTube channel

Related courses:

Ultimate Hacklab Self Paced




Leave your thought here

This site uses Akismet to reduce spam. Learn how your comment data is processed.