Utilize the netstat -an command to identify IPs with current concurrent requests exceeding 100. Then, automatically add IPs not on the whitelist to the DROP rule.
Create a file named deny_1.sh and insert the following command statements.
#!/bin/bash
if [[ -z $1 ]];then
num=100
else
num=$1
fi
cd $(cd $(dirname $BASH_SOURCE) && pwd)
iplist=`netstat -an |grep ^tcp.*:80|egrep -v 'LISTEN|127.0.0.1'|awk -F"[ ]+|[:]" '{print $6}'|sort|uniq -c|sort -rn|awk -v str=$num '{if ($1>str){print $2} fi}'`
if [[ ! -z $iplist ]];
then
for black_ip in $iplist
do
ip_section=`echo $black_ip | awk -F"." '{print $1"."$2"."$3}'`
grep -q $ip_section ./white_ip.txt
if [[ $? -eq 0 ]];then
echo $black_ip >>./recheck_ip.txt
else
iptables -nL | grep $black_ip || iptables -I INPUT -s $black_ip -j DROP
echo $black_ip >>./black_ip.txt
fi
done
fi
After saving, execute the following statements:
chmod +x deny_1.sh
sh deny_1.sh
Intercepted IPs will be recorded in black_ip.txt. If there are whitelisted IPs to be excluded, add these IPs to white_ip.txt, one per line.
Identify attacker IPs from web server logs based on their access patterns, and filter them out using iptables, excluding the local machine IP: 127.0.0.1.
Create a file named deny_2.sh and add the following command statements.
#!/bin/bash
OLD_IFS=$IFS
IFS=$'\n'
for status in `cat 网站访问日志路径 | grep '特征字符' | grep -v '127.0.0.1' | awk '{print $1}' |sort -n | uniq -c | sort -n -r | head -20`
do
IFS=$OLD_IFS
NUM=`echo $status | awk '{print $1}'`
IP=`echo $status | awk '{print $2}'`
if [ -z "`iptables -nvL | grep "dpt:80" | awk '{print $8}' | grep "$IP"`" ];then
if [ $NUM -gt 250 ];then
/sbin/iptables -I INPUT -p tcp -s $IP --dport 80 -j DROP
fi
fi
done
After saving, execute the following statements:
chmod +x deny_2.sh
sh deny_2.sh
Finally, add this to the cron job using crontab -e to execute every 20 minutes.
*/20 * * * * /root/deny_ip1.sh >dev/null 2>&1
23-02-2024 02:02:07
22-02-2024 03:19:32
22-02-2024 03:16:03
22-02-2024 03:14:03
22-02-2024 03:11:58