Python Security Lab: Lesson 8
Network Reconnaissance: Building a Custom Port Scanner
In Lesson 7, we built a URL auditor. Today, we dive deeper into the network layer. In the cybersecurity world of 2026, Reconnaissance is 70% of the job. We will use Python’s `socket` library to scan a target host for open ports, identifying potential entry points for security audits.
What is a Port Scanner?
A port scanner is an application that probes a server or host for open ports. Think of it as knocking on every door of a building to see which ones are unlocked. In 2026, securing your open ports is critical to preventing unauthorized access to cloud and local services.
import socket
from datetime import datetime
def scan_host(target, ports):
print(f"[*] Starting Scan on {target} at {datetime.now()}")
try:
for port in ports:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(0.5) # Fast scanning speed
result = s.connect_ex((target, port))
if result == 0:
print(f"[+] Port {port} is OPEN")
s.close()
except Exception as e:
print(f"[-] Scan Error: {e}")
# Define Target and common ports to check
target_ip = "127.0.0.1" # Localhost for testing
common_ports = [21, 22, 80, 443, 8080, 3306]
scan_host(target_ip, common_ports)
Understanding the Socket Library
The `socket` library is the backbone of Python network programming. The function `connect_ex` is particularly useful for security tools because it returns an error indicator (0 for success) instead of throwing an exception, making your scanner faster and more reliable.
Ethical Note & Best Practices
At Spider Cyber Team, we advocate for ethical hacking. Use this tool only on networks you own or have explicit permission to test. In 2026, unauthorized port scanning can be flagged as malicious intent by modern AI-based Intrusion Detection Systems (IDS).
Unlock Elite Python Skills
Get the Lesson 8 source code and participate in our weekly CTF challenges.
JOIN @SpiderTeam_EN ON TELEGRAM
Comments
Post a Comment