During a DDoS attack, identifying and blocking suspicious IP addresses quickly is important. The Bash script below finds the 50 most frequent IP addresses from the last 10 minutes, displays them and prepares a blocking list.
#!/bin/bash
# Установите временной диапазон
ten_minutes_ago=$(date -d "10 minutes ago" +"%d/%b/%Y:%H:%M:%S")
count=50
echo "========== $count =========="
# Фильтруем логи за последние 10 минут и обрабатываем их
awk -v time="$ten_minutes_ago" '$0 > time {print $1}' sitename.access.log | sort | uniq -c | sort -nr | head -n "$count"
echo "========== $count =========="
# Фильтруем логи за последние 10 минут, обрабатываем их и преобразуем в нужный формат
awk -v time="$ten_minutes_ago" '$0 > time {print $1}' sitename.access.log | sort | uniq -c | sort -nr | head -n "$count" | awk '{split($2, a, "."); print "deny " a[1]"."a[2]"."a[3]".0/24;"}' | sort -uThe script performs these steps:
- Sets a time range covering the last 10 minutes.
- Filters logs for that period and selects the 50 most active IP addresses.
- Converts the selected addresses into a format suitable for blocking.
Use this script to respond quickly to DDoS attacks and help protect your server.