I checked /var/log/auth.log on a server last week and found 1,247 failed SSH login attempts from the past 48 hours. A handful of IPs had tried over 200 usernames each. No surprise — public SSH endpoints get constant brute force. But knowing the numbers changed how I prioritised fail2ban rules.
This script parses auth.log (or journalctl output piped to stdin), counts every failed attempt per IP and username, and prints a summary table. No dependencies beyond Python 3 — runs on any Linux box with an SSH server.
GitHub: github.com/mzulfahmy/ssh-failed-login-monitor (the exact file from this post).
Better than grepping by hand because it aggregates everything in one pass: top attacking IPs sorted by volume, every username the attackers tried, a per-hour heatmap for spotting patterns, and a security recommendation at the end based on attempt count.
- Python 3.6+ (standard library only)
- Read access to
/var/log/auth.logorjournalctloutput piped in - Optional: cron for scheduled runs
#!/usr/bin/env python3
"""
ssh-failed-login-monitor.py — Parse auth.log for failed SSH login attempts
and produce a summary report: top attacking IPs, usernames tried, time
distribution, and overall stats.
Usage:
python3 ssh-failed-login-monitor.py /var/log/auth.log
journalctl -u sshd --since yesterday --no-pager | python3 ssh-failed-login-monitor.py - # pipe mode
"""
import sys
import re
import os
from collections import Counter, defaultdict
from datetime import datetime
def parse_auth_log(file_path: str) -> dict:
"""Parse an auth.log (or stdin via '-') and return structured results."""
pattern = re.compile(
r'(?P\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+\S+\s+sshd\[\d+\]:\s+'
r'Failed password for (?:invalid user\s+)?(?P\S+)\s+from\s+'
r'(?P\d{1,3}(?:\.\d{1,3}){3})\s+port\s+\d+\s+ssh2'
)
results = {
"total_lines": 0,
"failed_attempts": 0,
"ip_counter": Counter(),
"username_counter": Counter(),
"hour_counter": Counter(),
"invalid_users": set(),
"samples": [],
}
def process_line(line: str):
results["total_lines"] += 1
m = pattern.search(line)
if m:
results["failed_attempts"] += 1
ip = m.group("ip")
username = m.group("username")
results["ip_counter"][ip] += 1
results["username_counter"][username] += 1
# Extract hour
try:
hour = int(m.group("timestamp").split()[-1].split(":")[0])
results["hour_counter"][hour] += 1
except (IndexError, ValueError):
pass
if "invalid user" in line:
results["invalid_users"].add(username)
# Keep some samples
if len(results["samples"]) < 5:
results["samples"].append(line.strip())
if file_path == "-":
for line in sys.stdin:
process_line(line)
else:
with open(file_path, "r") as f:
for line in f:
process_line(line)
return results
def print_report(results: dict) -> None:
"""Print a human-readable report to stdout."""
print("=" * 60)
print(" SSH Failed Login Monitor Report")
print("=" * 60)
print(f"\n Lines scanned: {results['total_lines']}")
print(f" Failed attempts: {results['failed_attempts']}")
print(f" Invalid users: {len(results['invalid_users'])}")
print(f"\n{'─' * 40}")
print(" Top 10 Attacking IPs")
print(f"{'─' * 40}")
print(f" {'IP':<20} {'Attempts':>8} {'%':>6}")
print(f" {'─' * 34}")
total = results["failed_attempts"] or 1
for ip, count in results["ip_counter"].most_common(10):
pct = count / total * 100
print(f" {ip:<20} {count:>8} {pct:>5.1f}%")
print(f"\n{'─' * 40}")
print(" Top 10 Usernames Tried")
print(f"{'─' * 40}")
for user, count in results["username_counter"].most_common(10):
print(f" {user:<20} {count:>4}")
print(f"\n{'─' * 40}")
print(" Attacks by Hour")
print(f"{'─' * 40}")
for hour in sorted(results["hour_counter"]):
bar = "█" * min(results["hour_counter"][hour], 30)
print(f" {hour:02d}:00 {bar} ({results['hour_counter'][hour]})")
print(f"\n{'─' * 40}")
print(" Sample Log Lines (Failed)")
print(f"{'─' * 40}")
for s in results["samples"]:
print(f" {s[:130]}")
print(f"\n{'─' * 40}")
print(" Summary")
print(f"{'─' * 40}")
if results["failed_attempts"] > 0:
top_ip = results["ip_counter"].most_common(1)[0]
top_user = results["username_counter"].most_common(1)[0]
print(f" Most active attacker: {top_ip[0]} ({top_ip[1]} attempts)")
print(f" Most tried username: {top_user[0]} ({top_user[1]} times)")
print(f" Unique attacking IPs: {len(results['ip_counter'])}")
print(f" Unique usernames: {len(results['username_counter'])}")
# Security recommendation
print(f"\n {'▸' if results['failed_attempts'] > 10 else '✓'} ", end="")
if results["failed_attempts"] > 50:
print("High attack volume — consider fail2ban or rate-limiting.")
elif results["failed_attempts"] > 10:
print("Moderate activity — fail2ban recommended.")
else:
print("Low attack volume — baseline is normal.")
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} (for stdin)")
sys.exit(1)
file_path = sys.argv[1]
if file_path != "-" and not os.path.isfile(file_path):
print(f"Error: file not found: {file_path}")
sys.exit(1)
results = parse_auth_log(file_path)
print_report(results)

Run it on real data:
python3 ssh-failed-login-monitor.py /var/log/auth.logOr pipe journalctl output (useful on systemd-only distros without a traditional auth.log):
journalctl -u sshd --since "7 days ago" --no-pager | python3 ssh-failed-login-monitor.py -
Synthetic test run. The data above comes from a generated auth.log using RFC 5737 TEST-NET IP ranges (192.0.2.x, 198.51.100.x, 203.0.113.x) to demonstrate the output. Here is a sample of the generated log:
Nov 26 09:00:00 myserver sshd[1771]: Failed password for plesk from 192.0.2.99 port 22 ssh2
Nov 26 09:00:29 myserver sshd[3621]: Failed password for test from 192.0.2.99 port 22 ssh2
Nov 26 11:00:00 myserver sshd[5119]: Failed password for cpanel from 198.51.100.78 port 22222 ssh2
Nov 26 12:00:00 myserver sshd[4015]: Failed password for zabbix from 203.0.113.42 port 22 ssh2Pair this with an sshd_config audit to harden SSH before the first login attempt, and a fail2ban report script to see how many of those attackers actually got blocked. For broader SSH hardening, this OpenSSH hardening guide covers key exchange algorithms, disable-root-login automation, and rate limiting.
Drop the script into a cron job (daily or weekly) and pipe the output to a log file — having last week’s numbers when you check the server gives you a real baseline instead of guessing whether someone’s banging on the door more than usual.