SSH is the primary access point to your server, making it the most targeted service by attackers. Regularly auditing SSH logs helps you detect brute-force attacks, unauthorized access attempts, and compromised accounts.
Where SSH Logs Live
# Ubuntu/Debian
/var/log/auth.log
# RHEL/AlmaLinux/Rocky
/var/log/secure
# systemd journal
journalctl -u sshdFinding Failed Login Attempts
# Count failed password attempts
grep "Failed password" /var/log/auth.log | wc -l
# Show failed attempts with IPs
grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -20
# Show failed attempts with usernames
grep "Failed password" /var/log/auth.log | awk '{print $(NF-5)}' | sort | uniq -c | sort -rn | head -20
# Find attempts using invalid usernames (dictionary attacks)
grep "Invalid user" /var/log/auth.log | wc -lFinding Successful Logins
# List all successful logins
grep "Accepted" /var/log/auth.log
# Successful key-based logins
grep "Accepted publickey" /var/log/auth.log
# Successful password logins (should be zero if password auth is disabled)
grep "Accepted password" /var/log/auth.log
# Recent logins
last -20
# Failed logins
lastb -20Suspicious Patterns to Watch For
- Successful login from new IP — Could indicate compromised credentials
- Successful password login — Should not happen if key auth is enforced
- Login at unusual hours — Logins at 3 AM when no one should be working
- Multiple users from same IP — Credential stuffing attack
- Login followed by privilege escalation — su or sudo after login
- Session with no commands — Possible tunnel/proxy usage
Automated Monitoring Script
#!/bin/bash
# ssh-audit.sh — Daily SSH audit report
LOGFILE="/var/log/auth.log"
echo "=== SSH Audit Report $(date) ==="
echo ""
echo "--- Failed Logins (last 24h) ---"
grep "Failed password" "$LOGFILE" | tail -100 | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -10
echo ""
echo "--- Successful Logins (last 24h) ---"
grep "Accepted" "$LOGFILE" | tail -50
echo ""
echo "--- Invalid User Attempts ---"
grep "Invalid user" "$LOGFILE" | tail -20 | awk '{print $8}' | sort | uniq -c | sort -rn | head -10
echo ""
echo "--- Currently Logged In ---"
whoHardening SSH Based on Audit Findings
# Install fail2ban to auto-block brute force
sudo apt install fail2ban
sudo systemctl enable --now fail2ban
# Configure fail2ban for SSH
# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh
filter = sshd
maxretry = 3
bantime = 3600
findtime = 600
# Block repeated offenders permanently
# After 3 bans, block for 30 days
[recidive]
enabled = true
bantime = 2592000
findtime = 86400
maxretry = 3Setting Up Real-Time Alerts
# Use pam_exec to trigger alerts on login
# Add to /etc/pam.d/sshd:
# session optional pam_exec.so /usr/local/bin/login-alert.sh
# /usr/local/bin/login-alert.sh
#!/bin/bash
if [ "$PAM_TYPE" = "open_session" ]; then
echo "SSH Login: $PAM_USER from $PAM_RHOST at $(date)" | \
mail -s "SSH Login Alert" admin@example.com
fi