Denizhalil

Creating a Port Scanning Tool with Python

Introduction

Port scanning is a method used to determine open ports on target systems within a computer network. Port scanning tools are commonly employed in network security testing and provide system administrators with the ability to identify potential security vulnerabilities within their networks. In this article, you will learn how to create your own port scanning tool using the Python programming language.
before starting the article; I recommend you to read our article, what is an ip address and how does it work?

Step 1: Importing Required Libraries

To build our port scanning tool, we will utilize libraries such as socket and threading in Python. The socket library is used for establishing network connections and transmitting data, while the threading library is employed for creating parallel processes.

import socket
import threading

Step 2: Creating the Scanning Function

We will create a function that performs the scanning operation. This function will attempt to establish a connection on the specified IP address and port number, and if the connection is successful, it will indicate that the port is open.

def port_scan(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((ip, port))
        print(f"Port {port} is open")
    except:
        pass
    finally:
        sock.close()

Step 3: Initiating the Scanning Process

To perform the scanning operation, we will create a loop within the main program. This loop will send the range of specified ports to the scanning function.
Note: this is a basic tool. The advanced version of the tool has been shared on my github address.

def main():
    ip = input("Enter the IP address: ")
    start_port = int(input("Enter the starting port: "))
    end_port = int(input("Enter the ending port: "))

    for port in range(start_port, end_port + 1):
        threading.Thread(target=port_scan, args=(ip, port)).start()

Step 4: Running the Program

Add the following code to run the main program:

if __name__ == "__main__":
    main()

Step 5: Usage example

After saving the program to a file, I saved it to a file called port-scan.py. You can run it as in the example below.


python3 port-scan.py
Enter the IP address: 10.0.2.12
Enter the starting port: 21
Enter the ending port: 443
Port 21 is open
Port 22 is open
Port 23 is open
Port 25 is open
Port 53 is open
Port 80 is open
Port 111 is open
Port 139 is open

Conclusion

By following the above steps, you can create your own Python-based port scanning tool. This tool will scan ports on a specified IP address and inform you whether they are open or closed. You can further enhance this basic port scanning tool to perform more complex and customized scans.

Leave a Comment

Join our Mailing list!

Get all latest news, exclusive deals and academy updates.