| Blog ,frontpge

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.

Examples

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(‘127.0.0.1′, ’21-443’)

Method result

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

nmScan.command_line()

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

nmScan.scaninfo()

get all hosts that were scanned

nmScan.all_hosts()

get hostname for host 127.0.0.1

nmScan[‘127.0.0.1’].hostname()

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

nmScan[‘127.0.0.1’].state()

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

nmScan[‘127.0.0.1’].all_protocols()

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

nmScan[‘127.0.0.1’][‘tcp’].keys()

is there any information for port 22/tcp on host 127.0.0.1

nmScan[‘127.0.0.1’].has_tcp(22)

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

References:

https://pypi.org/project/python-nmap/

https://www.studytonight.com/network-programming-in-python/integrating-port-scanner-with-nmap