Port Scan Localhost Common Ports in Python
Scan common localhost ports (HTTP, HTTPS, SSH, FTP, and more) with a fast socket-based Python script that prints an open/closed status table.
Python code
33 linesimport socket
from datetime import datetime
COMMON_PORTS = {
80: "HTTP",
443: "HTTPS",
22: "SSH",
21: "FTP",
25: "SMTP",
3306: "MySQL",
5432: "PostgreSQL"
}
def scan_port(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.1)
try:
result = sock.connect_ex(("127.0.0.1", port))
return result == 0
finally:
sock.close()
def main():
print(f"Port scan started at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{'Port':<8} {'Service':<12} {'Status':<10}")
print("-" * 34)
for port, service in sorted(COMMON_PORTS.items()):
status = "OPEN" if scan_port(port) else "closed"
print(f"{port:<8} {service:<12} {status:<10}")
if __name__ == "__main__":
main()
Output
Port scan started at 2025-07-24 14:32:05
Port Service Status
----------------------------------
21 FTP closed
22 SSH closed
25 SMTP closed
80 HTTP open
443 HTTPS open
3306 MySQL closed
5432 PostgreSQL closed
How it works
This script uses socket.connect_ex() to test TCP connectivity without raising exceptions—it returns 0 when the port is open. The settimeout(0.1) makes the scan fast by capping how long each connection attempt waits. The finally block guarantees the socket closes even if an error occurs. The script prints results in a formatted table using f-strings, sorted by port number for readability.
Common mistakes
- Forgetting to close the socket, which leaks file descriptors
- Using `connect()` instead of `connect_ex()`, which throws exceptions on closed ports
- Scanning public IPs without permission—this script is for localhost only
- Setting too long a timeout, making the scan slow
Variations
- Use `sock.timeout = 0.01` for faster scans with less accuracy
- Replace `127.0.0.1` with a variable to scan remote hosts
Real-world use cases
- Checking which dev services are running locally before starting a project.
- Verifying firewall rules by confirming which ports are open on a test server.
- Monitoring a local machine for unexpected open ports as a basic security check.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.