Fail2ban is an essential tool for protecting Linux servers against brute-force attacks on SSH, FTP, and web applications. Combining Fail2ban with Telegram Bot API enables system administrators to receive instant real-time push notifications on mobile or desktop whenever an IP address is banned or unbanned.


Architecture Overview

  1. Fail2ban monitors log files (/var/log/auth.log, Nginx access logs, vsftpd logs).
  2. When ban thresholds are hit, Fail2ban triggers a custom action definition (/etc/fail2ban/action.d/telegram.conf).
  3. The action executes a lightweight shell script that sends formatted HTML messages via cURL to your Telegram Bot API endpoint.

Step 1 — Script Setup

Create a dedicated script directory and script /etc/fail2ban/scripts/fail2ban-telegram.sh:

#!/usr/bin/env bash

TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
CHAT_ID="YOUR_TELEGRAM_CHAT_ID"

ACTION="$1"
JAIL="$2"
IP="$3"

HOST="$(hostname -f)"
NOW="$(date +'%Y-%m-%d %H:%M:%S')"

if [ "$ACTION" = "ban" ]; then
    TEXT="🚫 <b>[Fail2ban Alert] IP Banned</b>%0A<b>Host:</b> $HOST%0A<b>Jail:</b> $JAIL%0A<b>IP:</b> $IP%0A<b>Time:</b> $NOW"
elif [ "$ACTION" = "unban" ]; then
    TEXT="✅ <b>[Fail2ban Alert] IP Unbanned</b>%0A<b>Host:</b> $HOST%0A<b>Jail:</b> $JAIL%0A<b>IP:</b> $IP%0A<b>Time:</b> $NOW"
fi

curl -s -X POST "https://api.telegram.org/bot${TOKEN}/sendMessage" \
    -d "chat_id=${CHAT_ID}" \
    -d "parse_mode=HTML" \
    -d "text=${TEXT}" > /dev/null

Make the script executable:

chmod +x /etc/fail2ban/scripts/fail2ban-telegram.sh

Step 2 — Fail2ban Action Configuration

Create /etc/fail2ban/action.d/telegram.conf:

[Definition]
actionban = /etc/fail2ban/scripts/fail2ban-telegram.sh ban <name> <ip>
actionunban = /etc/fail2ban/scripts/fail2ban-telegram.sh unban <name> <ip>

Step 3 — Enabling Action in jail.local

In /etc/fail2ban/jail.local, include telegram in your jail action:

[sshd]
enabled = true
port = ssh
filter = sshd
maxretry = 3
findtime = 600
bantime = 3600
action = iptables-multiport[name=SSH, port=ssh, protocol=tcp]
         telegram

Restart Fail2ban service:

systemctl restart fail2ban

Whenever a brute-force attempt triggers a ban, an instant Telegram notification arrives with host details, jail name, and offender IP address!