Build a Python Log Analyzer That Flags Suspicious Failed Logins
Every Linux server keeps a diary: /var/log/auth.log records every login attempt — successful and failed. Attackers probing your SSH are right there in the logs, if anyone looks. Most people never do. This script does it for you, every day, in seconds.
What We’re Building
A Python script that reads an auth log, finds failed login attempts, counts them per IP address, and flags the suspicious ones. Run it on your own server or a test VM. Never run this against logs you don’t own or have permission to analyze.
The Code
import refrom collections import CounterLOG_FILE = "/var/log/auth.log"THRESHOLD = 5 # flag IPs with more than 5 failed attemptsfailed_pattern = re.compile( r"Failed password.*from (\d+\.\d+\.\d+\.\d+)")def analyze_log(path): failed_ips = [] try: with open(path, "r") as f: for line in f: match = failed_pattern.search(line) if match: failed_ips.append(match.group(1)) except FileNotFoundError: print(f"Log file not found: {path}") return counts = Counter(failed_ips) print(f"Total failed attempts: {len(failed_ips)}") print(f"Unique IPs: {len(counts)}\n") print("Suspicious IPs (over threshold):") found = False for ip, count in counts.most_common(): if count > THRESHOLD: print(f" {ip} — {count} failed attempts") found = True if not found: print(" None. All quiet.")if __name__ == "__main__": analyze_log(LOG_FILE)
How It Works
- The regex hunts for
Failed password... from <IP>lines — the exact format SSH failures use in auth logs. Countertallies attempts per IP in one line.- Anything over the threshold gets flagged. Five failed logins from one IP could be you fat-fingering a password; fifty is someone’s script hammering your SSH.
Taking It Further
- Run it daily with cron for automatic monitoring.
- Add email alerts with Python’s
smtplibwhen a new IP crosses the threshold. - Feed flagged IPs to
fail2ban, which auto-blocks repeat offenders — real defense, automated.
The Defensive Point
This is what “threat hunting” looks like at its simplest: you didn’t buy a product, you read your own logs. Attackers rely on nobody watching. A 40-line script makes you the watcher.



Comments
Post a Comment