How to Build Port Scanner using Python: [2 Easy Examples]

Introduction

In this tutorial, we will learn about how to build port scanner using Python using 2 easy examples. Port scanning is very common task that is performed by network security experts. We can use utilities provided by Linux to do the port scanning or develop our own custom tool to do the same job using any programming languages. We will learn about building such tool using Python as Python provides  socket module which has many inbuilt function using which it becomes quite easy to do the port scanning on any target machines. Let us first understand some basics of socket before developing the tool. Let’s get started.

 

How to Build Port Scanner using Python: [2 Easy Examples]

What is Port Scanning?

Port scanning is a method in network security and system administration to identify open ports on a system or network device. Port scanning involves sending network packets to a target host and observing how the target responds. The primary purpose of port scanning is to discover which services or applications are running on a system and to identify potential vulnerabilities. Some of the usage of port scanning are listed below.

Security Assessment:  Network administrators and security professionals use port scanning to assess the security of their networks and systems. By identifying open ports, they can determine which services are exposed and might need additional security measures.

Troubleshooting:  Port scanning helps to diagnose network connectivity issues. If a specific service is not working, port scanning can reveal whether the port associated with the service is open or not.

Vulnerability Assessment:  Security professionals uses port scanning to discover potential vulnerability. For example, an open port running an outdated service might be susceptible to known exploits.

Penetration Testing:  Ethical hackers and penetration testers use port scanning as part of their assessment to find entry points into a system and assess its security posture.

 

Socket Module Overview

Also read: How to Install Cockpit on CentOS 7: [7 Easy Steps]

Python provides a module called ‘socket’ which offers low-level network communication functionality and allows us to create and interact with network sockets. Sockets are endpoints for sending or receiving data across a network and they are fundamental building block for network programming. Socket module comes up with many built-in functions that are useful for writing the socket programming in python. Some of the built-in socket module functions are:

bind() : Binds the socket to a specific address and port.
accept() : Accepts an incoming connection, creating a new socket for communication.
listen() : Puts the socket into listening mode for incoming connections.
connect() : Connects the socket to a remote server.
send() : Sends data over the socket.
recv() : Receives data from the socket.
close() :  Closes the socket when communication is completed .

 

How to Build Port Scanner using Python: [2 Easy Examples]

Also read: Python Files and Directories Managment

We will create a tool in Python which will do the port scanning on any target machine or website which are reachable from our host machine.  I have written the code in Python3 though it should also work with Python2 with some minor changes to the code.

Prerequisite

  • Linux Operating System
  • Python3 Installed

Python Code for Port Scan

#!/bin/python3

from socket import *
from termcolor import colored

portSock = socket(AF_INET, SOCK_STREAM)
setdefaulttimeout(1)
targetHost = input("Enter Host IP to scan the ports: ")


def portScanner(port):
    if  portSock.connect_ex((targetHost, port)) == 0:
        print(colored("Port %d is Open" %port, 'green'))

for port in range(1, 10000):
    portScanner(port)
Let us understand the above code.

 

  1. We have imported all the functions of socket module using ‘from socket import *’.
  2. We have imported ‘colored‘ function from ‘termcolor’ module to add coloring to our text .
  3. We have created a socker object ‘portSock‘ using socket() function from socket module. It accepts two input argument, AF_INET (used for IPv4 addresses) and SOCK_STREAM (used for tcp packet to perform the connection ).
  4. We have set a timeout for 1 second in case ports are not reachable using setdefaulttimeout() function.
  5. We have created a variable ‘targetHost‘ in which we will store the  input provided by the user. User will provide the IP address where port scanning will happen.
  6. We have created a function ‘portScanner()’ which accepts port as an input argument. It uses ‘connect_ex() ‘ function to attempt to connect to the  specified ‘port’ on the ‘targetHost‘ . It the connection is successfull, it will return ‘0’, indicating that the port is open.
  7. At last, we have created a for loop to scan ‘n’ number of ports using range() function.

 

Let us now execute the code and see how it works . But before execution this code, let us first check which all ports are open in our system using ‘nmap‘ Linux utility as shown below.

[[email protected] python]# nmap -sT -p- 10.29.151.138

Starting Nmap 6.40 ( http://nmap.org ) at 2023-09-03 12:41 IST
Nmap scan report for 10.29.151.138
Host is up (0.00074s latency).
Not shown: 65533 closed ports
PORT     STATE  SERVICE
22/tcp   open   ssh
9090/tcp open   zeus-admin
-sT: tells nmap to only scan TCP ports
-p- : used to scan the ports till range 65535. If this flag is not used, nmap will only scan ports till 1000.

 

As we see, there are only two tcp ports open. So when we execute out python code, it should also return the same output. Execute the code as shown below Provide your system IP address when it pops up for user input as shown below.

 

Example-1: Port Scanning on Localhost

[[email protected] python]# python3 port-scanner.py
OUTPUT
Enter Host IP to scan the ports: 10.29.151.138
Port 22 is Open
Port 9090 is Open
As we see, we got the same output as we had seen using nmap.

 

Example-2: Port Scanning on a Website

Let us scan the port one more time but this time we will scan on some random website instead of localhost.  I am using google.com to scan. I will execute nslookup command to get the IP of domain name ‘google.com’ as shown below.

[[email protected] python]# nslookup google.com
Server: 10.171.0.1
Address: 10.171.0.1#53

Non-authoritative answer:
Name: google.com
Address: 216.58.211.238
Name: google.com
Address: 2a00:1450:4026:805::200e

 

Next, we will check how many ports are open for google.com . We will scan the ports from 1- 1000. This can be achieved by excluding the ‘-p-‘ flag in below command. We will observe that two ports are open i.e 80 and 443.

[[email protected] python]# nmap -sT 216.58.211.238

Starting Nmap 6.40 ( http://nmap.org ) at 2023-09-03 12:52 IST
Nmap scan report for mad07s20-in-f14.1e100.net (216.58.211.238)
Host is up (0.0048s latency).
Not shown: 998 filtered ports
PORT     STATE  SERVICE
80/tcp   open   http
443/tcp  open   https

 

Let us now execute the python code and see if it returns the similar output. Change the range in Python code from 10,000 to 500 before executing the code below. We will see that it returns the same expected output.

OUTPUT

[[email protected] python]# python3 port-scanner.py
Enter Host IP to scan the ports: 216.58.211.238
Port 80 is Open
Port 443 is Open

 

Summary

This is very simple way to scan the ports  locally or on any website that are reachable. Although this code will not be suitable for production environment, you can definitely use it in your development environment. You can learn more about socket programming from python.org.

 

Leave a Comment