#!/bin/bash
# Configuration
NGINX_LOG="/patch-to/nginx/logs/access.log " # Path to Nginx log file
NGINX_CONF="/patch-to/bin/nginx/conf/blacklist.conf" # Path to Nginx blacklist file
BLOCK_LIMIT=10 # Maximum number of allowed requests in a short period
CHECK_INTERVAL=60 # Check interval (in seconds)
LOCK_FILE="/tmp/block_iptv_attackers.lock" # Prevents script from running multiple times
# Check if the script is already running
if [ -f "$LOCK_FILE" ]; then
echo "Script is already running."
exit 1
fi
# Create a lock file to prevent multiple script instances
touch "$LOCK_FILE"
# Extract IPs that accessed player_api.php, get.php, or api.php too many times
echo "Checking Nginx logs for attackers..."
# Find IPs with more than $BLOCK_LIMIT requests within a short time period
SUSPICIOUS_IPS=$(grep -E "player_api.php|get.php|api.php" "$NGINX_LOG" | \
awk '{print $1}' | sort | uniq -c | sort -nr | awk -v limit="$BLOCK_LIMIT" '$1 > limit {print $2}')
# Check if there are any suspicious IPs to block
if [ -z "$SUSPICIOUS_IPS" ]; then
echo "No suspicious IPs found."
else
echo "Suspicious IPs:"
echo "$SUSPICIOUS_IPS"
# Add suspicious IPs to the Nginx blacklist if not already blocked
for IP in $SUSPICIOUS_IPS; do
if ! grep -q "$IP" "$NGINX_CONF"; then
echo "Blocking IP: $IP"
echo "deny $IP;" >> "$NGINX_CONF"
else
echo "IP $IP is already blocked."
fi
done
# Reload Nginx configuration to apply the new blacklist
echo "Reloading Nginx..."
/patch-to/bin/nginx/sbin/nginx -s reload
fi
# Remove the lock file to allow future script executions
rm -f "$LOCK_FILE"
echo "Script execution finished."