Skip to content

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.

Terminal window
apt update
apt install fail2ban -y

Enable and start the service:

Terminal window
systemctl enable --now fail2ban

Check that it is running:

Terminal window
systemctl status fail2ban

Create a local configuration file:

Terminal window
nano /etc/fail2ban/jail.local

Add this basic SSH configuration:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
findtime = 10m
bantime = 1h

If your SSH port is not 22, replace port = ssh with your port:

port = 2222

Restart Fail2ban:

Terminal window
systemctl restart fail2ban

Show enabled jails:

Terminal window
fail2ban-client status

Show SSH jail details:

Terminal window
fail2ban-client status sshd

You will see how many IPs are currently banned and which IPs are listed.

If you accidentally ban yourself, use the hosting panel console or another trusted IP to run:

Terminal window
fail2ban-client set sshd unbanip <ip-address>

Example:

Terminal window
fail2ban-client set sshd unbanip 203.0.113.10