Python Nmap Module Fully Explained with 8 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 

1. 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. 

2. UDP Scanning Using Nmap –

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.’ 

3. COMPREHENSIVE Scanning Using Nmap Python-

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.  

4. Regular Scanning Using Nmap –

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

5. OS DETECTION Using Nmap Python

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.

6. Multiple IP Range Using Nmap Python

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.

7. Ping Scan Scanning Using Nmap

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).

8. Python nmap Asynchronous Using Nmap

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!

Subscribe
Notify of
guest
11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Prince
Prince
3 years ago

It threw key error when I change ip addr

Python Pool
Admin
3 years ago
Reply to  Prince

Do you input an IP outside of the network?

ami
ami
2 years ago

I tried the code, only option 7 is available,
all other return the following message:
in analyse_nmap_xml_scan
  raise PortScannerError(nmap_err)
nmap.nmap.PortScannerError: ‘You requested a scan type which requires root privileges.\nQUITTING!\n’

Pratik Kinage
Admin
2 years ago
Reply to  ami

You need to run your Python code as an administrator to get results. In windows, you can do this by opening a command prompt using “Run as Administrator” option. In Linux, you can do this by using the “sudo” command.

Regards,
Pratik

ami
ami
2 years ago
Reply to  Pratik Kinage

Thanks for addressing my question. I’m using a Mac…Already tried sudo su in terminal…with no results 🙁

Pratik Kinage
Admin
2 years ago
Reply to  ami

sudo command should work in Mac. Can you check if your user account has admin privileges? Check this guide if it helps support.apple.com

Regards,
Pratik

seret
seret
2 years ago

hey i’m trying to run the code but it’s writing scanner = nmap.PortScanner()
AttributeError: module ‘nmap’ has no attribute ‘PortScanner’
can you help?

seret
seret
2 years ago

Hey i’m trying to run the code but it’s writing scanner = nmap.PortScanner()
AttributeError: module ‘nmap’ has no attribute ‘PortScanner’
can you help?

Pratik Kinage
Admin
2 years ago
Reply to  seret

pip uninstall nmap
pip install python-nmap

This will solve it.

hackerregmi
hackerregmi
2 years ago

How u did OS detection?

Pratik Kinage
Admin
2 years ago
Reply to  hackerregmi

You can select option 5 to get OS info.