Skip to content
Automation

SSH Login Audit Script: Detect Brute-Force Attacks in Python (2027)

Copy-paste a defensive SSH login audit script in Python to parse auth.log or journald, flag brute-force IPs, run --dry-run, and send webhook alerts in 2027.

Updated: 10 min read 1 views
Share: Facebook X LinkedIn WhatsApp

A defensive ssh login audit script gives Linux administrators immediate visibility into credential-stuffing bots, invalid-user scans, and anomalous password logins across public-facing servers without installing heavy SIEM agents. Every server exposed on port 22 attracts automated SSH probes within minutes of booting, burying real security signals—such as an unexpected Accepted password login or a sudden brute-force burst from a single subnet—inside thousands of routine log lines.

Worse, modern Linux distributions split authentication logs between /var/log/auth.log, /var/log/secure, and systemd-journald. Built for Ubuntu 22.04+, Debian 12+, and RHEL 9+ hosts running Python 3.10+, the zero-dependency script below auto-detects your log source, correlates failed attempts with successful logins from the same IP, supports CIDR allowlisting and a safe --dry-run mode, outputs terminal tables or --json reports, and dispatches Slack or Discord webhook alerts.

Key Takeaways & Script Specs

  • Runtime & Dependencies: Python 3.10+ standard library only (re, ipaddress, subprocess, urllib.request)—zero pip installs required.
  • Supported Log Sources: Auto-detects /var/log/auth.log (Debian/Ubuntu), /var/log/secure (RHEL/Rocky), or falls back to journalctl -u ssh / sshd.
  • Detection Rules: Flags high-volume failed password IPs, invalid-user scanners, and high-severity “failure followed by Accepted” compromise indicators.
  • Safety Controls: Strictly read-only auditing (never modifies firewall rules automatically), CIDR allowlisting, --dry-run testing, and non-zero exit codes on alerts.

Why Raw Grep and Fail2Ban Logs Miss Compromise Signals

Most server operators install Fail2Ban and assume SSH monitoring is solved. While Fail2Ban blocks noisy IPs after a fixed retry count, it does not alert you when an attacker switches to slow, distributed password guessing below the ban threshold—or worse, when a legacy account with password authentication enabled actually succeeds after ten failed attempts. Running grep "Failed password" /var/log/auth.log by hand also fails on modern Ubuntu 24.04+ or RHEL 9+ minimal cloud images that route sshd events exclusively to systemd-journald rather than flat files.

To audit SSH reliably, you need to correlate both failed and accepted events across all log backends and compare them against your hardened OpenSSH sshd_config(5) manual settings (such as PasswordAuthentication no and MaxAuthTries). By querying journalctl(1) time-windowed units or flat auth logs with a single Python parser, you turn noisy authentication streams into an actionable daily or hourly security digest.

Architecture and Read-Only Audit Flow

Our audit script follows a strictly read-only, non-destructive pipeline so it can run safely on production bastions without risking accidental lockouts:

+-------------------------------------------------------------------+

|  1. Select Source: --log-file OR Auto-Detect auth.log/secure/     |
|---|
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  2. Parse OpenSSH Events & Filter Allowlisted CIDRs               |
|     - Failed password / Invalid user / Accepted (publickey|pass)  |
|     - Skip trusted VPN/office CIDRs via Python ipaddress module   |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  3. Correlate Threats & Thresholds                                |
|     - Brute-force IP (>= --fail-threshold attempts)               |
|     - Accepted password logins (if --flag-password-logins)        |
|     - Critical: Same IP had failures AND Accepted login           |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  4. Output Table / --json + Send Webhook Alert (unless --dry-run) |
+-------------------------------------------------------------------+

This defensive audit layer pairs cleanly with your existing Linux observability stack. Alongside a systemd service monitor script watching daemon crashes and an Nginx log analyzer script tracking HTTP 5xx and scanner bursts, auditing SSH logins closes the host-access visibility gap.

Comparing SSH Auditing Approaches in 2027

Before deploying an audit job, compare how the four common SSH monitoring methods balance setup complexity, false-positive noise, and compromise detection.

Auditing ApproachReads Both Flat Logs & JournaldDetects Fail-Then-SuccessZero External DependenciesRisk of Self-Lockout
Manual grep / lastbManual switchingNo (manual correlation)YesNone
Fail2Ban Default JailsYesNo (bans only)No (daemon + nftables)Medium (without whitelist)
Full Wazuh / OSSEC AgentYesYesNo (heavy SIEM server)Low
Python Read-Only Audit ScriptYes (auto-detects)Yes (correlates per IP)Yes (Python stdlib)Zero (read-only alerts)

Notice how Python’s built-in ipaddress library documentation lets you exclude corporate VPN subnets or bastion jump hosts cleanly with CIDR notation before computing brute-force counts.

Prerequisites and Environment Setup

Because the script uses only Python 3.10+ standard library modules, no virtual environment or pip install is required. Create a dedicated directory and a 0600 environment file for your allowlisted CIDRs and Slack/Discord webhook URL:

sudo mkdir -p /opt/ssh-login-audit
sudo chown "$USER":"$USER" /opt/ssh-login-audit
cd /opt/ssh-login-audit

cat <<'EOF' > /opt/ssh-login-audit/.env
SSH_ALLOWLIST=127.0.0.0/8,10.0.0.0/8
SSH_FAIL_THRESHOLD=10
WEBHOOK_URL=https://hooks.slack.com/services/REPLACE/ME/NOW
EOF
chmod 600 /opt/ssh-login-audit/.env

Make sure the account running the audit can read authentication logs—either via a root-owned systemd timer or by adding your audit user to the adm and systemd-journal groups.

Complete Production Python SSH Login Audit Script

Save the following script as /opt/ssh-login-audit/ssh_login_audit.py. It auto-detects /var/log/auth.log, /var/log/secure, or journalctl, correlates failed attempts against accepted logins per IP, flags any password-based logins when --flag-password-logins is enabled, and supports --dry-run and --json output.

#!/usr/bin/env python3
"""
Production SSH Login Audit Script (2027)
Read-only, zero-dependency Python auditor that inspects auth.log, secure,
or systemd-journald for brute-force SSH bursts and suspicious accepted logins.
"""

import argparse
import ipaddress
import json
import logging
import os
import re
import socket
import subprocess
import sys
import urllib.error
import urllib.request
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Iterable, List, Optional

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("ssh_login_audit")

FAILED_RE = re.compile(
r"(?:Failed\s+(?P<method>\S+)\s+for\s+(?:invalid\s+user\s+)?(?P<user>\S+)\s+from\s+(?P<ip>\S+)"
r"|Invalid\s+user\s+(?P<inv_user>\S+)\s+from\s+(?P<inv_ip>\S+))"
)
ACCEPTED_RE = re.compile(
r"Accepted\s+(?P<method>\S+)\s+for\s+(?P<user>\S+)\s+from\s+(?P<ip>\S+)"
)

def iter_auth_lines(log_file: Optional[str], minutes: int) -> Iterable[str]:
"""Yield sshd log lines from an explicit file, standard auth log, or journalctl."""
if log_file:
path = Path(log_file)
if not path.is_file():
raise FileNotFoundError(f"Log file not found: {log_file}")
with path.open("r", encoding="utf-8", errors="replace") as handle:
for line in handle:
if "sshd" in line:
yield line
return

# Try systemd-journald first when minutes window is specified
for unit in ("ssh", "sshd"):
    try:
        proc = subprocess.run(
            [
                "journalctl",
                "-u",
                unit,
                "--since",
                f"{minutes} minutes ago",
                "--no-pager",
                "-o",
                "short-iso",
            ],
            capture_output=True,
            text=True,
            timeout=10,
            check=False,
        )
        if proc.returncode == 0 and proc.stdout.strip():
            for line in proc.stdout.splitlines():
                yield line
            return
    except (FileNotFoundError, subprocess.TimeoutExpired):
        break

for candidate in (Path("/var/log/auth.log"), Path("/var/log/secure")):
    if candidate.is_file():
        with candidate.open("r", encoding="utf-8", errors="replace") as handle:
            for line in handle:
                if "sshd" in line:
                    yield line
        return

raise RuntimeError("No readable auth.log, secure, or journalctl SSH entries found.")

def is_allowlisted(ip_str: str, networks: List[ipaddress._BaseNetwork]) -> bool:
"""Return True if ip_str is valid and falls inside any allowlisted CIDR."""
try:
addr = ipaddress.ip_address(ip_str)
except ValueError:
return True  # Ignore malformed tokens safely
return any(addr in net for net in networks)

def run_audit(
log_file: Optional[str],
minutes: int,
allowlist_cidrs: List[str],
fail_threshold: int,
flag_password_logins: bool,
) -> dict:
"""Parse SSH authentication events and identify brute-force or compromise signals."""
networks = [ipaddress.ip_network(c.strip(), strict=False) for c in allowlist_cidrs if c.strip()]

failed_by_ip: Counter = Counter()
users_by_ip: Dict[str, Counter] = defaultdict(Counter)
accepted_events: List[dict] = []
total_failed = 0
total_accepted = 0

for line in iter_auth_lines(log_file, minutes):
    f_match = FAILED_RE.search(line)
    if f_match:
        ip = f_match.group("ip") or f_match.group("inv_ip")
        user = f_match.group("user") or f_match.group("inv_user") or "unknown"
        if ip and not is_allowlisted(ip, networks):
            total_failed += 1
            failed_by_ip[ip] += 1
            users_by_ip[ip][user] += 1
        continue

    a_match = ACCEPTED_RE.search(line)
    if a_match:
        ip = a_match.group("ip")
        user = a_match.group("user")
        method = a_match.group("method")
        if ip and not is_allowlisted(ip, networks):
            total_accepted += 1
            accepted_events.append({"ip": ip, "user": user, "method": method})

brute_force_ips = []
for ip, count in failed_by_ip.most_common():
    if count >= fail_threshold:
        top_users = [u for u, _ in users_by_ip[ip].most_common(3)]
        brute_force_ips.append({"ip": ip, "failed_attempts": count, "targeted_users": top_users})

suspicious_accepts = []
for ev in accepted_events:
    prior_fails = failed_by_ip.get(ev["ip"], 0)
    reasons = []
    if prior_fails > 0:
        reasons.append(f"followed_{prior_fails}_failures")
    if flag_password_logins and ev["method"] == "password":
        reasons.append("password_auth_used")
    if reasons:
        suspicious_accepts.append({**ev, "reasons": reasons})

alerts_triggered = bool(brute_force_ips or suspicious_accepts)

return {
    "host": socket.gethostname(),
    "timestamp_utc": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ"),
    "window_minutes": minutes,
    "total_failed": total_failed,
    "total_accepted": total_accepted,
    "brute_force_ips": brute_force_ips[:15],
    "suspicious_accepts": suspicious_accepts,
    "alerts_triggered": alerts_triggered,
}

def send_webhook(webhook_url: str, report: dict, dry_run: bool) -> None:
"""Dispatch a Slack/Discord alert summary using Python standard library urllib."""
if not report["alerts_triggered"]:
return

lines = [
    f"*[SSH Login Audit Alert]* `{report['host']}` (last {report['window_minutes']}m) | "
    f"Failed: {report['total_failed']} | Accepted: {report['total_accepted']}"
]
for ev in report["suspicious_accepts"][:5]:
    lines.append(
        f"- CRITICAL: `{ev['user']}@{ev['ip']}` via `{ev['method']}` ({', '.join(ev['reasons'])})"
    )
for item in report["brute_force_ips"][:5]:
    lines.append(
        f"- BRUTE FORCE: `{item['ip']}` ({item['failed_attempts']} fails; users: {', '.join(item['targeted_users'])})"
    )

message = "\n".join(lines)
if dry_run:
    logger.info("[DRY-RUN] Would send webhook:\n%s", message)
    return

body = json.dumps({"text": message, "content": message}).encode("utf-8")
req = urllib.request.Request(
    webhook_url,
    data=body,
    headers={"Content-Type": "application/json", "User-Agent": "myscrpts-ssh-audit/1.0"},
    method="POST",
)
try:
    with urllib.request.urlopen(req, timeout=5) as resp:
        if resp.status >= 400:
            logger.warning("Webhook returned HTTP %d", resp.status)
except urllib.error.URLError as exc:
    logger.error("Webhook delivery failed: %s", exc)

def print_report(report: dict) -> None:
"""Print an aligned SSH audit summary to stdout."""
print(
f"Host: {report['host']} | Window: {report['window_minutes']}m | "
f"Failed: {report['total_failed']} | Accepted: {report['total_accepted']}"
)
if report["suspicious_accepts"]:
print("\nSuspicious Accepted Logins:")
for ev in report["suspicious_accepts"]:
print(f"  {ev['user']}@{ev['ip']} ({ev['method']}) -> {', '.join(ev['reasons'])}")
if report["brute_force_ips"]:
print("\nBrute-Force Source IPs:")
print(f"  {'IP ADDRESS':<22} {'FAILS':<8} {'TARGETED USERS'}")
for row in report["brute_force_ips"]:
print(f"  {row['ip']:<22} {row['failed_attempts']:<8} {', '.join(row['targeted_users'])}")
if not report["alerts_triggered"]:
print("\nNo brute-force bursts or suspicious logins detected.")

def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Read-only SSH login audit script for auth.log, secure, and journald."
)
parser.add_argument("--log-file", help="Optional explicit path to auth.log or secure")
parser.add_argument(
"--minutes",
type=int,
default=60,
help="Journald lookback window in minutes (default: 60)",
)
parser.add_argument(
"--allowlist",
default=os.getenv("SSH_ALLOWLIST", "127.0.0.0/8,::1/128"),
help="Comma-separated CIDR ranges to ignore",
)
parser.add_argument(
"--fail-threshold",
type=int,
default=int(os.getenv("SSH_FAIL_THRESHOLD", "10")),
help="Failed attempts per IP required to flag brute force (default: 10)",
)
parser.add_argument(
"--flag-password-logins",
action="store_true",
help="Alert on any Accepted password login (recommended for key-only hosts)",
)
parser.add_argument("--json", action="store_true", help="Emit JSON report")
parser.add_argument(
"--dry-run",
action="store_true",
help="Print report and log webhook payload without sending HTTP requests",
)
return parser.parse_args()

def main() -> int:
args = parse_args()
allowlist = [c.strip() for c in args.allowlist.split(",") if c.strip()]
try:
report = run_audit(
log_file=args.log_file,
minutes=args.minutes,
allowlist_cidrs=allowlist,
fail_threshold=args.fail_threshold,
flag_password_logins=args.flag_password_logins,
)
except (FileNotFoundError, RuntimeError) as exc:
logger.error("%s", exc)
return 2

if args.json:
    print(json.dumps(report, indent=2))
else:
    print_report(report)

webhook_url = os.getenv("WEBHOOK_URL")
if webhook_url and report["alerts_triggered"]:
    send_webhook(webhook_url, report, dry_run=args.dry_run)

return 1 if report["alerts_triggered"] else 0

if name == "main":
sys.exit(main()

Team MyScrpts

Team MyScrpts is the editorial and engineering collective behind myscrpts.com — publishing tested PHP, JavaScript, Python, and Bash scripts, automation workflows, WordPress templates, and AI developer tools.

Leave a Reply

Your email address will not be published. Required fields are marked *

Stay ahead of the curve. Zero spam.

Get our weekly curation of tested scripts, DevOps blueprints, and new dev tools.