From Novice to Network Sentinel: Building Your Own High-Speed Python Port Scanner in One Day + Video

Listen to this Post

Featured Image

Introduction:

In the high-stakes world of cybersecurity, the difference between a secure network and a breach often lies in visibility. Security analysts rely on port scanning as a fundamental reconnaissance technique to discover open doors (ports) and running services on a network, effectively mapping an organization’s attack surface. While tools like Nmap are industry standards, understanding the underlying mechanics by building a custom, multi-threaded port scanner in Python provides invaluable insight into socket programming, network protocols, and the attacker’s mindset—turning theoretical knowledge into a practical, deployable asset for any Blue Team member.

Learning Objectives:

  • Understand the core principles of TCP/IP networking and socket programming in Python.
  • Implement multi-threading to significantly accelerate the network scanning process.
  • Develop banner grabbing techniques to identify software versions and potential vulnerabilities.
  • Learn to assess and classify security risks based on exposed services.

You Should Know:

1. Laying the Foundation: The Single-Threaded Scanner

Before racing ahead, we must understand the basics. A port scanner attempts to establish a connection to a target IP address on a specific port. If the connection is successful, the port is “open.” In Python, this is achieved using the `socket` library.

Start by creating a simple script that scans a range of ports sequentially. This is slow but illustrates the core logic.

import socket
from datetime import datetime

def scan_port(target, port):
"""Attempts to connect to a target port."""
try:
 Create a socket object (IPv4, TCP)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(0.5)  Set a short timeout
 Connect to the target and port
result = sock.connect_ex((target, port))
if result == 0:  0 means success
return True
else:
return False
sock.close()
except socket.error:
return False

if <strong>name</strong> == "<strong>main</strong>":
target = input("Enter target IP: ")
print(f"Scanning target: {target}")
start_time = datetime.now()

for port in range(1, 1025):  Scan first 1024 ports
if scan_port(target, port):
print(f"Port {port}: Open")

end_time = datetime.now()
print(f"Scan completed in: {end_time - start_time}")

This foundational script shows how `socket.connect_ex()` attempts a handshake. A return code of `0` indicates success. Running this will highlight the major drawback: sequential scanning is painfully slow.

2. Supercharging Performance with Multi-threading

To transform this educational script into a production-ready tool, we must implement multi-threading. This allows the program to check many ports simultaneously, drastically reducing scan time. The core idea is to create a pool of worker threads that grab ports from a queue.

We’ll use the `threading` and `queue` libraries to manage this. Here’s how to integrate it:

import threading
import queue
import socket

target = '127.0.0.1'  Replace with your target
open_ports = []
print_lock = threading.Lock()
q = queue.Queue()

def scan_port(port):
"""Function to be run by each thread."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(0.5)
result = sock.connect_ex((target, port))
if result == 0:
with print_lock:  Prevents messy console output
print(f"[+] Port {port} is open")
open_ports.append(port)
sock.close()
except Exception as e:
pass

def threader():
"""Worker function to get a port from the queue and scan it."""
while True:
worker = q.get()
scan_port(worker)
q.task_done()

Create and start the thread pool (e.g., 100 threads)
for x in range(100):
t = threading.Thread(target=threader, daemon=True)
t.start()

Put all ports to be scanned into the queue
for port in range(1, 65536):
q.put(port)

Wait until the queue is empty
q.join()
print(f"\n[+] Scan complete. Open ports: {sorted(open_ports)}")

This multi-threaded version can scan all 65,535 ports in a fraction of the time it takes the sequential script, a critical feature for any real-world security assessment.

  1. Beyond Open Ports: Service Identification with Banner Grabbing
    Knowing a port is open is useful, but knowing what service (e.g., Apache 2.4.49, OpenSSH 7.4) is running behind it is golden. This is done through “banner grabbing”—sending a probe and analyzing the response.

We can modify our `scan_port` function. After a successful connection, we send a generic probe (like a newline for HTTP or a null byte) and receive the initial banner sent back by the service.

def grab_banner(sock):
"""Attempt to receive a banner from the socket."""
try:
 Send a probe (e.g., a newline for many services)
sock.send(b'\n')
banner = sock.recv(1024).decode().strip()
return banner
except:
return None

Inside scan_port, after confirming the port is open:
if result == 0:
banner = grab_banner(sock)
with print_lock:
if banner:
print(f"[+] Port {port} is open - Service: {banner}")
else:
print(f"[+] Port {port} is open - Service: Unknown")

This simple addition turns a basic scanner into a powerful information-gathering tool. A banner like “220 ProFTPD 1.3.5e Server” immediately flags a potentially outdated and vulnerable service.

4. Automating Risk Assessment

The next step is to add logic to classify risk. We can create a dictionary of known vulnerable service versions and compare them against the banners we grab.

 Define known risky versions
RISK_SIGNATURES = {
'vsftpd 2.3.4': 'Critical (Backdoor)',
'OpenSSH 7.2p2': 'High (Known vulnerabilities)',
'ProFTPD 1.3.5': 'High (Mod_copy vulnerability)',
}

Inside your banner printing logic:
risk_level = 'Low'
for signature, level in RISK_SIGNATURES.items():
if signature.lower() in banner.lower():
risk_level = level
break
print(f"[+] Port {port} is open - Service: {banner} [Risk: {risk_level}]")

This automates the initial triage, allowing a SOC analyst to immediately focus on the most critical exposures without manually verifying every single service.

5. Deployment and Ethical Use (Linux/Windows)

Prabin’s tool is open source and ready for deployment. On any system with Python 3 installed, you can clone and run it.

Linux/macOS:

git clone https://github.com/prabinb/advanced-port-scanner.git  Hypothetical URL from post
cd advanced-port-scanner
python3 scanner.py -t <target_ip> -p 1-1000

Windows (Command Prompt or PowerShell):

git clone https://github.com/prabinb/advanced-port-scanner.git
cd advanced-port-scanner
python scanner.py -t <target_ip> -p 1-1000

The `-t` and `-p` arguments would be parsed using Python’s `argparse` library to provide a clean command-line interface, making the tool accessible for any analyst.

6. Hardening Against Your Own Tool

Understanding how this scanner works is the first step to defending against it. A Blue Teamer can use this knowledge to implement mitigations:
– Firewall Rules (Linux – iptables): Limit the rate of connection attempts to detect and block scans.

iptables -I INPUT -p tcp --dport 1:1000 -m connlimit --connlimit-above 10 --connlimit-mask 32 -j DROP

– Port Knocking: Hide services by having them closed by default. They only open if a specific sequence of connection attempts (“knocks”) is received.
– Service Hardening: Change default banners to give away less information. For example, in Apache, you can set `ServerTokens Prod` in `httpd.conf` to send a minimal banner.

What Undercode Say:

  • Build to Defend: Creating offensive security tools like a port scanner is not about enabling attacks; it’s about deeply understanding the mechanics of reconnaissance. This knowledge allows defenders to better configure firewalls, intrusion detection systems, and harden services against real threats.
  • Automation is Key: In modern Security Operations Centers (SOCs), manual work is a bottleneck. Automating tasks like port scanning, banner grabbing, and initial risk assessment frees up analysts to focus on complex incident response and threat hunting, drastically improving an organization’s security posture.

This project exemplifies the hands-on, continuous learning ethic that defines the cybersecurity field. By moving from a consumer of security tools to a creator, you gain a profound advantage in protecting digital assets. The journey from a simple idea to a deployed, multi-threaded scanner in one day is a testament to the power of practical application in mastering network security.

Prediction:

The line between development and security operations will continue to blur. We will see a rise in “Security Tooling Engineers”—specialists who don’t just use off-the-shelf software but build custom, highly optimized internal tools tailored to their organization’s unique architecture. The future SOC analyst will be expected to code, automate, and build, making projects like this port scanner a baseline expectation rather than a standout achievement.

▶️ Related Video (78% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Bkprabin Cybersecurity – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky