Open In App

Port scanner using ‘python-nmap’

Last Updated : 21 Apr, 2020
Like Article

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 ( as your target


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 = ''
# 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}.')


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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads