Fail2Ban
Fail2ban monitors logs and blocks IPs that show malicious behavior.
# Ubuntu/Debiansudo apt install fail2ban
# RHEL/CentOSsudo yum install epel-release && sudo yum install fail2banCreate /etc/fail2ban/jail.local:
[DEFAULT]bantime = 3600findtime = 600maxretry = 3destemail = your_email@example.comsendername = Fail2Banaction = %(action_mwl)s
[sshd]enabled = trueport = 2222filter = sshdlogpath = /var/log/auth.log# logpath = /var/log/secure # RHEL/CentOSmaxretry = 3bantime = 3600sudo systemctl enable fail2bansudo systemctl start fail2ban
# Status and managementsudo fail2ban-client status sshdsudo fail2ban-client get sshd bannedsudo fail2ban-client set sshd unbanip 192.168.1.100SSH Client Config
On your local machine, ~/.ssh/config:
Host production-server HostName server_ip Port 2222 User deployer IdentityFile ~/.ssh/id_prod_server ServerAliveInterval 60 ServerAliveCountMax 3
Host staging-server HostName staging_ip Port 2222 User deployer IdentityFile ~/.ssh/id_staging_server ProxyJump bastion-hostssh production-serverLog Monitoring
# Real-timesudo tail -f /var/log/auth.log # Ubuntu/Debiansudo tail -f /var/log/secure # RHEL/CentOS
# Failed attemptssudo grep "Failed password" /var/log/auth.log | tail -20
# Successful loginssudo grep "Accepted publickey" /var/log/auth.log | tail -20Monitoring Script
Save as /usr/local/bin/ssh-monitor.sh:
#!/bin/bashLOG_FILE="/var/log/auth.log"REPORT_FILE="/var/log/ssh-security-report.txt"
echo "SSH Security Report - $(date)" > $REPORT_FILEecho "================================" >> $REPORT_FILEecho "" >> $REPORT_FILE
echo "Failed Login Attempts:" >> $REPORT_FILEgrep "Failed password" $LOG_FILE | awk '{print $1, $2, $3, $11}' | sort | uniq -c | sort -nr | head -20 >> $REPORT_FILEecho "" >> $REPORT_FILE
echo "Successful Logins:" >> $REPORT_FILEgrep "Accepted publickey" $LOG_FILE | awk '{print $1, $2, $3, $9, $11}' | tail -20 >> $REPORT_FILEecho "" >> $REPORT_FILE
echo "Active SSH Sessions:" >> $REPORT_FILEwho >> $REPORT_FILEecho "" >> $REPORT_FILE
echo "Current Fail2Ban Bans:" >> $REPORT_FILEfail2ban-client status sshd 2>/dev/null >> $REPORT_FILE
cat $REPORT_FILEsudo chmod +x /usr/local/bin/ssh-monitor.sh
# Daily email reportecho "0 9 * * * /usr/local/bin/ssh-monitor.sh | mail -s 'SSH Security Report' your_email@example.com" | sudo crontab -Next Steps
Proceed to the Troubleshooting and Best Practices guide.