Linux

Simple Port Scanning using Python

Port Scanning using Python

In the realm of network security, understanding how to identify open ports on a system is crucial. Port scanning is a fundamental technique used by network administrators and security professionals to assess the security posture of a network. This article will guide you through the process of creating a simple port scanner using Python, providing you with the knowledge and tools necessary to perform effective network assessments.

Understanding Ports

Before diving into the technical aspects of port scanning, it’s essential to understand what ports are and why they matter in network communications.

What are Ports?

A port is a virtual point where network connections start and end. They serve as communication endpoints for sending and receiving data between devices over a network. Each port is associated with a specific service or application, allowing multiple services to run simultaneously on a single device.

Commonly Used Ports

There are several well-known ports that serve specific functions:

  • HTTP (Port 80): Used for web traffic.
  • HTTPS (Port 443): Secure web traffic.
  • FTP (Port 21): File Transfer Protocol for transferring files.
  • SSH (Port 22): Secure Shell for secure remote access.

Why Scan Ports?

Port scanning is performed for various reasons:

  • Security Assessments: Identifying open ports can help detect vulnerabilities that could be exploited by attackers.
  • Network Troubleshooting: Scanning can help diagnose connectivity issues by identifying which services are running.
  • Inventory Management: Understanding which services are active on a network aids in managing resources effectively.

Prerequisites for Building a Port Scanner

Before you begin coding your port scanner, ensure you have the following prerequisites in place:

Required Software

  • Python: You will need Python installed on your machine. Python 3.x is recommended for this project.
  • IDEs/Text Editors: Use an Integrated Development Environment (IDE) like PyCharm or a text editor like Visual Studio Code to write your code.

Libraries Needed

The primary library required for this project is the socket library, which provides access to the BSD socket interface. Optionally, you may use argparse for command-line argument parsing and colorama for colored output in the terminal.

Setting Up the Python Environment

This section outlines how to set up your Python environment effectively.

Installing Python

The installation process varies depending on your operating system:

  • Windows: Download the installer from the official Python website and run it. Make sure to check the box that says “Add Python to PATH.”
  • macOS: Use Homebrew by running /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)", then install Python with brew install python.
  • Linux: Most distributions come with Python pre-installed. If not, use your package manager, e.g., sudo apt install python3.

Setting Up the IDE

Select an IDE or text editor that you are comfortable with. For beginners, Visual Studio Code is highly recommended due to its user-friendly interface and extensive plugin support. Install any necessary extensions for Python development to enhance your coding experience.

Building the Basic Port Scanner

The following steps will guide you through creating a basic port scanner in Python.

Step 1: Importing Libraries

Your first step is to import the necessary libraries. Open your IDE or text editor and create a new Python file named port_scanner.py. Start by importing the socket library:

import socket

Step 2: Defining the Target

You need to specify which IP address or hostname you want to scan. You can prompt the user for input using the following code snippet:

target = input("Enter the host to scan: ")

Step 3: Creating a Function to Check Ports

The core functionality of your port scanner involves checking whether specific ports are open or closed. Create a function called is_port_open():

def is_port_open(target, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    result = s.connect_ex((target, port))
    return result == 0

This function creates a socket connection to the target IP address at the specified port. If it successfully connects, it returns True; otherwise, it returns False.

Step 4: Scanning a Range of Ports

You can now implement logic to scan a range of ports. For example, let’s scan ports from 1 to 1024:

for port in range(1, 1025):
    if is_port_open(target, port):
        print(f"Port {port} is open")
    else:
        print(f"Port {port} is closed")

This loop iterates through each port in the specified range and calls the is_port_open() function to check its status.

Your basic scanner works; however, there are ways to enhance its functionality significantly.

Add Multithreading for Speed

A single-threaded scanner can be slow when checking many ports. To speed up the process, implement multithreading using Python’s threading library. Here’s how you can do it:

from threading import Thread

def scan_thread(port):
    if is_port_open(target, port):
        print(f"Port {port} is open")

threads = []
for port in range(1, 1025):
    thread = Thread(target=scan_thread, args=(port,))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

This modification creates a new thread for each port being scanned, allowing multiple connections to occur simultaneously.

Add flexibility by allowing users to specify target IP addresses and ports directly from the command line using argparse:

import argparse

parser = argparse.ArgumentParser(description="Simple Port Scanner")
parser.add_argument("target", help="Target IP address")
args = parser.parse_args()
target = args.target

This approach enables users to run your script with different targets without modifying the source code each time.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button