π οΈ Python Port Scanning Tutorial: Build Your Own Scanner

π Table of Contents
- Introduction
- Prerequisites
- Building a Basic Port Scanner
- Enhancing the Scanner with Threading
- Advanced Features
- Best Practices
- Common Use Cases
- Troubleshooting
- Additional Resources
- π Friendly Links
π§ Introduction
Port scanning is a critical technique in network diagnostics and cybersecurity. It helps identify which ports are open on a host and what services may be running. By building your own scanner in Python, youβll learn more about:
- TCP connections
- Networking protocols
- Threading for performance
π Prerequisites
Before starting, ensure you have:
- Python 3.x installed
- Familiarity with:
- Basic Python syntax
- Sockets and the TCP/IP model
- A terminal or IDE to run your code
- Authorization to scan your chosen target IP (scanning external networks without permission is illegal)
π§ Building a Basic Port Scanner
Let’s create a simple scanner that checks for open TCP ports from 1 to 1024.
β Step 1: Import Required Libraries
python import socket
from datetime import datetime
β Step 2: Define the Target
python
target = input("Enter the host to be scanned: ")
β Step 3: Port Scanning Loop
python print(f"Scanning target {target}")
start_time = datetime.now()
for port in range(1, 1025):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target, port))
if result == 0:
print(f"Port {port}: Open")
s.close()
end_time = datetime.now()
print(f"Scanning completed in: {end_time - start_time}")
π§ͺ Test it locally using
127.0.0.1
orlocalhost
.
β‘ Enhancing the Scanner with Threading
Speed up the scan using Pythonβs threading
module.
β Step 1: Add Threading
python
import threading
β Step 2: Define a Threaded Scan Function
python def scan_port(port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target, port))
if result == 0:
print(f"Port {port}: Open")
s.close()
except:
pass
β Step 3: Launch Multiple Threads
python for port in range(1, 1025):
thread = threading.Thread(target=scan_port, args=(port,))
thread.start()
π§ You can also use
concurrent.futures.ThreadPoolExecutor
for even more control.
π Advanced Features
π‘ 1. Banner Grabbing
pythondef grab_banner(port):
try:
s = socket.socket()
s.settimeout(2)
s.connect((target, port))
banner = s.recv(1024)
print(f"Port {port} Banner: {banner.decode().strip()}")
s.close()
except:
pass
π 2. Service Detection
python common_ports = {
21: 'FTP',
22: 'SSH',
23: 'Telnet',
25: 'SMTP',
53: 'DNS',
80: 'HTTP',
110: 'POP3',
443: 'HTTPS',
}
Use this mapping for user-friendly output.
πΎ 3. Save Results to File
python with open('scan_results.txt', 'a') as file:
file.write(f"Port {port}: Open\n")
β Best Practices
- β Only scan with permission
- β± Use reasonable timeouts (0.5β2 seconds)
- π Log results to avoid losing data
- π§― Handle exceptions to prevent crashes
π Common Use Cases
- π Security auditing & vulnerability scanning
- π₯ System monitoring by administrators
- π Educational learning in networking or cybersecurity courses
π§° Troubleshooting
Issue | Possible Solution |
---|---|
Slow scans | Use threading or asyncio |
Access denied | Use elevated privileges or avoid privileged ports |
No results | Check firewall or port filtering on the target |
π Additional Resources
- π₯ YouTube - Python Port Scanner Tutorial Build a Basic Port Scanner in Python (Tech With Tim)
- π GeeksforGeeks Guide Threaded Port Scanner
- π ThePythonCode.com Advanced Port Scanner in Python
- π§΅ AsyncIO Version Fast Python Port Scanner Using AsyncIO
π Friendly Links
Check out some tools and gear our community loves:
- π§΄ Okamoto Big Boy XL (3-Pack) β For comfort beyond expectations.
- πͺ’ 1⁄2 Arborist Rope β Blue/Black β Heavy-duty and highly durable rope for professionals.
- π₯ Tech With Timβs Python Tutorial β Great YouTube channel for Python learners.
- π Nmap - Network Scanner Tool β A professional-grade open-source scanner you should also explore.