#!/bin/bash# Define the threshold for packetsTHRESHOLD=5000# Define the IPset nameIPSET_NAME="blackhole"# Define the log fileLOG_FILE="/var/log/iptables.log"# Define the temporary file to store IPsTEMP_FILE="/tmp/blackhole_ips.txt"# Clear the temporary filetrue>"$TEMP_FILE"# Extract IPs with packet counts exceeding the thresholdiptables-vnL-x|awk-vthreshold="$THRESHOLD"' /Chain/ { chain=$2 } /DROP/ && chain ~ /FORWARD|INPUT/ && $1 > threshold { print $8 }'>>"$TEMP_FILE"# Add IPs to the IPset if they are not already presentwhileread-rip; doif!sudoipsettest"$IPSET_NAME""$ip">/dev/null2>&1; thensudoipsetadd"$IPSET_NAME""$ip"fidone<"$TEMP_FILE"# Apply blackhole route for IPs in the IPsetfor ip in$(sudo ipset list "$IPSET_NAME" |grep-v "Name:"); dosudoiprouteaddblackhole"$ip"||truedone# Clean uprm"$TEMP_FILE"