Python Nmap Module Fully Explained with Programs

Network Mapper or Nmap is a module in python which is used to create an open port scanner. It is better known as a foot-printing or reconnaissance tool. Reconnaissance in ethical hacking terms means finding information about the target. The target can be in the form of a website or IP address. We will perform this Reconnaissance using the python nmap module. 

Information can be the name of the operating system used or characteristics of the network devices. But the primary use of Nmap is to design an open port scanner. An open port scanner is used to scan what all ports are open and what all ports are closed.  

What is nmap in python? 

In technical terms, nmap is a tool that is used for security auditing and network discovery. The way nmap works is by sending raw IP packets to determine if the target host is available on the network, what services the target host is providing, what type of firewalls are in use, what operating system versions are running, and tons of other characteristics. 

We will do it all using python. Although there is a GUI tool available, the fun part is only when using a command line or python scripts. 

Syntax of Python Nmap- 

To use the nmap module in python, we first need to install the online tool. After installing it, we need to install the nmap module using pip install python-nmap.   

Note that we cannot target any website or IP address as that is illegal so that we will use the localhost i.e., 127.0.0.1 

Operations Performed using Nmap Python 

SYN-ACK Scanning using nmap python-

When we want to know about the state of the port without establishing the full connection, we perform SYN scanning. This is possible by sending synchronous packets to every port of the target host (for three-way handshaking). If the target host server responds with SYN/ACK (synchronization acknowledged), it means that the port is open. We will make a program for this type of scanning. 

UDP Scan-

User Datagram Packet is a connectionless protocol for video streaming or audio streaming purposes. It is fast but unreliable. We perform a UDP Scan when we want to search for UDP ports that are open or vulnerable. The process to know about the state is mostly the same as above. There are four types of state based on the responses.  

If we get a response, then the state is ‘OPEN.’ 

Response is not there , then the state is ‘OPEN|FILTER’ 

For ‘ICMP port unreachable error (type 3, code 3)’, then the state is ‘closed.’ 

And if we get ‘Other ICMP unreachable errors (type 3, code 1, 2, 9, 10, or 13)’, it means the state is ‘FILTERED.’ 

COMPREHENSIVE SCAN-

This scan does a lot of hard work in information gathering. Even if the handshake is not possible in the first attempt, it will keep trying, and if it gets success, it will try to know about the Operating System Version and other relevant information.  

Regular Scan-

A regular scan tries to find 1000 most common scans and uses the ICMP Echo request for host detection.  

OS DETECTION

Using nmap we can detect what OS does the target work on, and service detection for devices. It is possible by using the TCP/IP stack fingerprinting method. In our program, we get a lot of results when we try os detection, but we will only show you the relevant information.

Multiple IP Range

It is quite common that we will want to check the services of multiple hosts, so in nmap we have an option to give a range of ip addresses for scanning.

Ping Scan

Pinging means scanning if a host is active on the network or not. To check for more than one host, we perform ping sweep (also known as ICMP sweep).

Python nmap Asynchronous

In Asynchronous, results are returned one at a time to a callback function defined by the user.

Program For using Functionalities in Python Nmap

import nmap

scanner = nmap.PortScanner()

ip_addr = '127.0.0.1'

response = input("""\nPlease enter the type of scan you want to run
                1)SYN ACK Scan
                2)UDP Scan
                3)Comprehensive Scan
                4)Regular Scan
                5. OS Detection
                6. Multiple IP inputs
                7. Ping Scan\n""")
print("You have selected option: ", response)

# If user's input is 1, perform a SYN/ACK scan
if response == '1':
    print("Nmap Version: ", scanner.nmap_version())
    # Here, v is used for verbose, which means if selected it will give extra information
    # 1-1024 means the port number we want to search on
    #-sS means perform a TCP SYN connect scan, it send the SYN packets to the host
    scanner.scan(ip_addr,'1-1024', '-v -sS')
    print(scanner.scaninfo())
    # state() tells if target is up or down
    print("Ip Status: ", scanner[ip_addr].state())
    # all_protocols() tells which protocols are enabled like TCP UDP etc
    print("protocols:",scanner[ip_addr].all_protocols())
    print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
    
# If user's input is 2, perform a UDP Scan   
elif response == '2':
    # Here, v is used for verbose, which means if selected it will give #extra information
    # 1-1024 means the port number we want to search on
    #-sU means perform a UDP SYN connect scan, it send the SYN packets to #the host
    print("Nmap Version: ", scanner.nmap_version())
    scanner.scan(ip_addr, '1-1024', '-v -sU')
    print(scanner.scaninfo())
    # state() tells if target is up or down
    print("Ip Status: ", scanner[ip_addr].state())
    # all_protocols() tells which protocols are enabled like TCP UDP etc
    print("protocols:",scanner[ip_addr].all_protocols())
    print("Open Ports: ", scanner[ip_addr]['udp'].keys())
    
# If user's input is 3, perform a Comprehensive scan
elif response == '3':
    print("Nmap Version: ", scanner.nmap_version())
    # sS for SYN scan, sv probe open ports to determine what service and version they are running on
    # O determine OS type, A tells Nmap to make an effort in identifying the target OS
    scanner.scan(ip_addr, '1-1024', '-v -sS -sV -sC -A -O')
    print(scanner.scaninfo())
    print("Ip Status: ", scanner[ip_addr].state())
    print(scanner[ip_addr].all_protocols())
    print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
    
# If user's input is 4, perform a Regular Scan
elif response == '4':
    # Works on default arguments
    scanner.scan(ip_addr)
    print(scanner.scaninfo())
    print("Ip Status: ", scanner[ip_addr].state())
    print(scanner[ip_addr].all_protocols())
    print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
    
elif response == '5':
    print(scanner.scan("127.0.0.1", arguments="-O")['scan']['127.0.0.1']['osmatch'][1])

elif response == '6':
    ip_addr = input()
    print("Nmap Version: ", scanner.nmap_version())
    # Here, v is used for verbose, which means if selected it will give extra information
    # 1-1024 means the port number we want to search on
    #-sS means perform a TCP SYN connect scan, it send the SYN packets to the host
    scanner.scan(ip_addr,'1-1024', '-v -sS')
    print(scanner.scaninfo())
    # state() tells if target is up or down
    print("Ip Status: ", scanner[ip_addr].state())
    # all_protocols() tells which protocols are enabled like TCP UDP etc
    print("protocols:",scanner[ip_addr].all_protocols())
    print("Open Ports: ", scanner[ip_addr]['tcp'].keys())
    
elif response == '7': 
    scanner.scan(hosts='192.168.1.0/24', arguments='-n -sP -PE -PA21,23,80,3389')
    hosts_list = [(x, scanner[x]['status']['state']) for x in scanner.all_hosts()]
    for host, status in hosts_list:
        print('{0}:{1}'.format(host, status))
    
else:
    print("Please choose a number from the options above")

 

Output-

Let us give all the possible numbers (1-4) one by one.

Please enter the type of scan you want to run
                1)SYN ACK Scan
                2)UDP Scan
                3)Comprehensive Scan
                4)Regular Scan
1
You have selected option:  1
Nmap Version:  (7, 80)
{'tcp': {'method': 'syn', 'services': '1-1024'}}
Ip Status:  up
protocols: ['tcp']
Open Ports:  dict_keys([135, 137, 445])
Please enter the type of scan you want to run
                1)SYN ACK Scan
                2)UDP Scan
                3)Comprehensive Scan
                4)Regular Scan
2
You have selected option:  2
Nmap Version:  (7, 80)
{'udp': {'method': 'udp', 'services': '1-1024'}}
Ip Status:  up
protocols: ['udp']
Open Ports:  dict_keys([137, 500])
Please enter the type of scan you want to run
                1)SYN ACK Scan
                2)UDP Scan
                3)Comprehensive Scan
                4)Regular Scan
3
You have selected option:  3
Nmap Version:  (7, 80)
{'tcp': {'method': 'syn', 'services': '1-1024'}}
Ip Status:  up
['tcp']
Open Ports:  dict_keys([135, 137, 445])
python nmap
Please enter the type of scan you want to run
1)SYN ACK Scan
2)UDP Scan
3)Comprehensive Scan
4)Regular Scan
5)OS Detection
6)Multiple IP inputs
7) Ping Scan

5
{'name': 'Microsoft Windows 10 1703', 'accuracy': '93', 'line': '69394', 'osclass': [{'type': 'general purpose', 'vendor': 'Microsoft', 'osfamily': 'Windows', 'osgen': '10', 'accuracy': '93', 'cpe': ['cpe:/o:microsoft:windows_10:1703']}]}
Please enter the type of scan you want to run
1)SYN ACK Scan
2)UDP Scan
3)Comprehensive Scan
4)Regular Scan
5)OS Detection
6)Multiple IP inputs
7) Ping Scan

6
Please enter the type of scan you want to run
1)SYN ACK Scan
2)UDP Scan
3)Comprehensive Scan
4)Regular Scan
5)OS Detection
6)Multiple IP inputs
7) Ping Scan

7
192.168.1.0:up 
192.168.1.1:up 
192.168.1.10:up 
192.168.1.100:up 
192.168.1.101:up 
192.168.1.102:up
nmap python

Must Read:

Conclusion

There are so many other scans that you can do, like intense scan, quick scan, ping scan, which will just need small changes in the program that we made. You must have now acknowledged the power of map in python, how powerful a tool it is for information gathering.

Try to run the programs on your side and let us know if you have any queries.

Happy Coding!

Leave a Reply