Protect SSH with Fail2ban
Fail2ban watches login logs and temporarily blocks IP addresses that fail authentication too often. It is a useful extra layer of protection for SSH.
Install Fail2ban
Section titled “Install Fail2ban”apt updateapt install fail2ban -yEnable and start the service:
systemctl enable --now fail2banCheck that it is running:
systemctl status fail2banCreate a local SSH jail
Section titled “Create a local SSH jail”Create a local configuration file:
nano /etc/fail2ban/jail.localAdd this basic SSH configuration:
[sshd]enabled = trueport = sshfilter = sshdlogpath = /var/log/auth.logmaxretry = 5findtime = 10mbantime = 1hIf your SSH port is not 22, replace port = ssh with your port:
port = 2222Restart Fail2ban:
systemctl restart fail2banCheck status
Section titled “Check status”Show enabled jails:
fail2ban-client statusShow SSH jail details:
fail2ban-client status sshdYou will see how many IPs are currently banned and which IPs are listed.
Unban an IP address
Section titled “Unban an IP address”If you accidentally ban yourself, use the hosting panel console or another trusted IP to run:
fail2ban-client set sshd unbanip <ip-address>Example:
fail2ban-client set sshd unbanip 203.0.113.10