Build a Python Port Monitor That Alerts You When a New Port Opens
Servers change. A teammate installs a service, a package update starts a daemon, or an attacker plants a backdoor — and suddenly a port is open that wasn’t open yesterday. A port monitor catches that moment. Today we’ll build one in Python: it snapshots the open ports on your own machine, compares against the last snapshot, and alerts you on any change. Only ever run it against machines you own or administer.
The Idea
The script is simple: scan a list of common ports on localhost, save the result to a JSON file, and on the next run compare the new result with the saved one. Any port that appears or disappears gets reported. Run it on a schedule (cron, which we covered in an earlier post) and you have a free intrusion tripwire.
The Code
import socket
import json
import os
from datetime import datetime
HOST = "127.0.0.1"
PORTS = [21, 22, 23, 25, 53, 80, 110, 143, 443, 3306, 5432, 6379, 8080, 8443]
SNAPSHOT = "open_ports.json"
def scan():
open_ports = []
for port in PORTS:
s = socket.socket()
s.settimeout(0.5)
try:
s.connect((HOST, port))
open_ports.append(port)
except (socket.timeout, ConnectionRefusedError, OSError):
pass
finally:
s.close()
return open_ports
def main():
current = set(scan())
previous = set()
if os.path.exists(SNAPSHOT):
with open(SNAPSHOT) as f:
previous = set(json.load(f)["open_ports"])
new = sorted(current - previous)
closed = sorted(previous - current)
if new:
print(f"[!] NEW ports opened: {new}")
if closed:
print(f"[*] Ports closed since last run: {closed}")
if not new and not closed:
print("[+] No change — port state is stable.")
with open(SNAPSHOT, "w") as f:
json.dump({"host": HOST, "checked": datetime.now().isoformat(),
"open_ports": sorted(current)}, f, indent=2)
if __name__ == "__main__":
main()
How It Works
- Scanning — socket.connect() tries each port; a successful connection means something is listening. The 0.5-second timeout keeps the scan fast.
- Snapshotting — results are saved to open_ports.json, so the next run has a baseline to compare against.
- Diffing — set subtraction finds exactly what changed. New ports are the alert; closed ports are informational (a service stopped, or was removed).
- First run — with no snapshot file, everything looks “new.” That’s expected; the second run is your real baseline.
Automate It
Run it every hour with cron:
0 * * * * /usr/bin/python3 /home/anony/port_monitor.py >> /home/anony/port_monitor.log 2>&1
Pair it with an email or webhook alert for real monitoring, and extend the port list to cover services you actually run.
Why This Matters for Defense
Attackers who compromise a machine often open a listener — a reverse shell, a rogue web panel, a crypto miner’s API. Log-based detection misses it; a port diff catches it within the hour. It’s a tiny script with an outsized defensive payoff — and it’s the kind of automation that turns a Python learner into a security practitioner.



Comments
Post a Comment