一、屏蔽每分钟访问次数过多的ip
# 编写脚本
[root@openEuler-1 script]# vim deny_frequent_ip.sh
[root@openEuler-1 script]# cat deny_frequent_ip.sh
#!/bin/bash
#########################
#File name:deny_frequent_ip.sh
#Email:obboda@163.com
#Created time:2025-01-15 11:44:05
#Description:屏蔽每分钟访问次数过多的ip
#########################
LOG=/var/log/nginx/access.log
DATE=$(date +%d/%b/%Y:%H:%M)
cat $LOG | grep $DATE | awk '{IP[$1]++} END {for (k in IP) if (IP[k] > 10) print k}' > deny_ip
iptables -nL | tr -s " " | awk -F'[ :]' '/^DROP/ && $NF==80 {print $4}' > exist_deny_ip
while read line
do
if ! grep -w "$line" exist_deny_ip &> /dev/null
then
iptables -I INPUT -p tcp --dport 80 -s $line -j DROP
fi
done < deny_ip
rm -f deny_ip exist_deny_ip
# 创建计划任务(每分钟执行一次)
[root@openEuler-1 script]# crontab -e
crontab: installing new crontab
# 查看计划任务
[root@openEuler-1 script]# crontab -l
*/1 * * * * bash /server/script/deny_frequent_ip.sh
二、拒绝ssh暴力破解(一小时内大于5次)
# 编写脚本
[root@openEuler-1 script]# vim deny_frequent_ip_v2.sh
[root@openEuler-1 script]# cat deny_frequent_ip_v2.sh
#!/bin/bash
#########################
#File name:deny_frequent_ip_v2.sh
#Email:obboda@163.com
#Created time:2025-01-15 13:12:05
#Description:拒绝ssh暴力破解(一小时内大于5次)
#########################
DATE=$(date +"%b %d %H")
lastb | grep "$DATE" | awk '{IP[$3]++} END{for (k in IP) if (IP[k]>4) print k}' > deny_ip
iptables -nL | tr -s " " | awk -F'[ :]' '/^DROP/ && $NF==22 {print $4}' > exist_deny_ip
while read line
do
if ! grep -w "$line" exist_deny_ip &> /dev/null
then
iptables -I INPUT -p tcp --dport 22 -s $line -j DROP
fi
done < deny_ip
rm -f deny_ip exist_deny_ip
# 创建计划任务(每个小时执行一次)
[root@openEuler-1 script]# crontab -e
crontab: installing new crontab
# 查看计划任务
[root@openEuler-1 script]# crontab -l
*/1 * * * * bash /server/script/deny_frequent_ip.sh
* */1 * * * bash /server/script/deny_frequent_ip_v2.sh
# 删除计划脚本
[root@openEuler-1 script]# crontab -r
[root@openEuler-1 script]# crontab -l
no crontab for root