SHELL脚本实现通过访问日志过滤客户端IP,来针对Web站点的访问并发限制

#!/bin/bash

#Author:ldk
#Contact Mail:455436588@qq.com
#Version:3.0
#Company:COMPANY
#Create time:2019-07-17 17:31:58
#Description:Manual cleanup Linux OS cache

Max=100000
CFS=/usr/local/nginx/conf/nginx.conf
LOGS=/usr/local/nginx/logs/access.log

#执行循环体
#过滤出access.log日志里所定义的'$remote_addr'地址。重复的打印出来并排序;
cat $LOGS | awk '{print $2}' | sort -n | uniq -c | sort -rn | head -n 10 | while read line
do
#定义变量$IP,打印出是哪个IP;
IP=echo "$line" | awk '{print $2}'
#定义变量$Count,打印出这个IP出现的次数;
Count=echo "$line" | awk '{print $1}'
#定义变量$Docs,值为nginx的配置文件;
Docs=cat $conf_dir
#定义变量$Judges,看配置文件里有没有这个IP;
Judges=echo "$Docs" | grep "${IP}"

#判断,如果$Count的值大于$Max的值,并且在$Judges里为空,不是这也不是那,执行替换并写入到$Docs指定location下做deny操作,重载并continue;
if [[ $Count -gt $Max ]] && [[ $Judges == " " ]] && [[ $IP != "47.100.110.92" ]] && [[ $IP != "140.207.117.66" ]]
    then 
        sed -i  '/location \/ {/a\deny '${IP}';' $CFS
        sed -i  '/location \/files {/a\deny '${IP}';' $CFS
        sed -i  '/location \~\* \\\.apk\$ {/a\deny '${IP}';' $CFS
        sed -i  '/location \~\* \\\.mp4\*\$ {/a\deny '${IP}';' $CFS
        /usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx -s reload && echo "SUCCESS!!"
    else
        continue    
fi

done

上一篇:nginx deny 封IP


下一篇:ubuntu 默认防火墙安装、启用、查看状态