Skip to content

Instantly share code, notes, and snippets.

@tserj
Last active September 24, 2024 02:30
Show Gist options
  • Select an option

  • Save tserj/40bf40a1f0aa9f326325d92c466dec66 to your computer and use it in GitHub Desktop.

Select an option

Save tserj/40bf40a1f0aa9f326325d92c466dec66 to your computer and use it in GitHub Desktop.
how to ban IPs from nginx error log
#!/bin/bash
# Source and destination files
LOG_FILE="/var/log/nginx/error.log"
DENY_FILE="/etc/nginx/conf.d/deny.block"
# Temporary file to hold the new unique entries
TEMP_FILE=$(mktemp)
# Extract unique IPs from the error log excluding 0.0.0.0 and 185.32.132.29
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' "$LOG_FILE" \
| grep -vE '^(0\.0\.0\.0|185\.32\.132\.29)$' \
| sort \
| uniq > "$TEMP_FILE"
# Add new IPs to DENY_FILE if they don't already exist
while read -r ip; do
if ! grep -q "deny $ip;" "$DENY_FILE"; then
echo "deny $ip;" >> "$DENY_FILE"
fi
done < "$TEMP_FILE"
# Cleanup temporary file
rm -f "$TEMP_FILE"
# Check NGINX configuration and reload if successful
nginx -t && systemctl reload nginx

First of all, add include /etc/nginx/conf.d/deny.block; to your nginx configuration:

server {
    server_name _;

    root /usr/share/nginx/html/;
    index index.php index.html index.htm index.nginx-debian.html;

    # Include the deny.conf file here
    include /etc/nginx/conf.d/deny.block;

    location / {
        try_files $uri $uri/ =404;
    }
}

Then create ban_from_error_log.sh script below into /usr/local/bin/
and make it executable:

sudo chmod +x /usr/local/bin/ban_from_error_log.sh

Try to exec manually and then

Open the cron table for editing:

sudo crontab -e

Add the following line to schedule the script to run every 15 minutes:

*/15 * * * * /usr/local/bin/collect_ips.sh

verify cron job execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment