Skip to main content
Security Monitoring and Connection Management
Overview

Security Monitoring and Connection Management

2 min read

Fail2Ban

Fail2ban monitors logs and blocks IPs that show malicious behavior.

Terminal window
# Ubuntu/Debian
sudo apt install fail2ban
# RHEL/CentOS
sudo yum install epel-release && sudo yum install fail2ban

Create /etc/fail2ban/jail.local:

[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
destemail = your_email@example.com
sendername = Fail2Ban
action = %(action_mwl)s
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
# logpath = /var/log/secure # RHEL/CentOS
maxretry = 3
bantime = 3600
Terminal window
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
# Status and management
sudo fail2ban-client status sshd
sudo fail2ban-client get sshd banned
sudo fail2ban-client set sshd unbanip 192.168.1.100

SSH Client Config

On your local machine, ~/.ssh/config:

Terminal window
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-host
Terminal window
ssh production-server

Log Monitoring

Terminal window
# Real-time
sudo tail -f /var/log/auth.log # Ubuntu/Debian
sudo tail -f /var/log/secure # RHEL/CentOS
# Failed attempts
sudo grep "Failed password" /var/log/auth.log | tail -20
# Successful logins
sudo grep "Accepted publickey" /var/log/auth.log | tail -20

Monitoring Script

Save as /usr/local/bin/ssh-monitor.sh:

#!/bin/bash
LOG_FILE="/var/log/auth.log"
REPORT_FILE="/var/log/ssh-security-report.txt"
echo "SSH Security Report - $(date)" > $REPORT_FILE
echo "================================" >> $REPORT_FILE
echo "" >> $REPORT_FILE
echo "Failed Login Attempts:" >> $REPORT_FILE
grep "Failed password" $LOG_FILE | awk '{print $1, $2, $3, $11}' | sort | uniq -c | sort -nr | head -20 >> $REPORT_FILE
echo "" >> $REPORT_FILE
echo "Successful Logins:" >> $REPORT_FILE
grep "Accepted publickey" $LOG_FILE | awk '{print $1, $2, $3, $9, $11}' | tail -20 >> $REPORT_FILE
echo "" >> $REPORT_FILE
echo "Active SSH Sessions:" >> $REPORT_FILE
who >> $REPORT_FILE
echo "" >> $REPORT_FILE
echo "Current Fail2Ban Bans:" >> $REPORT_FILE
fail2ban-client status sshd 2>/dev/null >> $REPORT_FILE
cat $REPORT_FILE
Terminal window
sudo chmod +x /usr/local/bin/ssh-monitor.sh
# Daily email report
echo "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.

Share this post