Port scanner using ‘python-nmap’

In this article, we will learn how to program a port scanner using the ‘nmap‘ module in Python. The program will take a range of port numbers as input and print the state (open or closed) of all the ports in that range.

Nmap: Nmap is a free and open-source network scanning tool. To run the program discussed in this article, you will need to have ‘nmap’ tool installed in your system. If it is not installed, visit Nmap download page.

Modules used

We will be using the ‘python-nmap‘ module to achieve this task. Install the package (if not already installed) by the following command –

pip install python-nmap

Note: Doing ‘nmap’ scans on a target without proper permission and authority is illegal. Use localhost (127.0.0.1) as your target

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

import nmap
   
# take the range of ports to 
# be scanned
begin = 75
end = 80
  
# assign the target ip to be scanned to
# a variable
target = '127.0.0.1'
   
# instantiate a PortScanner object
scanner = nmap.PortScanner()
   
for i in range(begin,end+1):
   
    # scan the target port
    res = scanner.scan(target,str(i))
   
    # the result is a dictionary containing 
    # several information we only need to
    # check if the port is opened or closed
    # so we will access only that information 
    # in the dictionary
    res = res['scan'][target]['tcp'][i]['state']
   
    print(f'port {i} is {res}.')

chevron_right


Output:

port 75 is closed.
port 76 is closed.
port 77 is closed.
port 78 is closed.
port 79 is closed.
port 80 is open.

Note: The output can vary depending on the present status of the ports.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.