1、修改nginx配置文件:
vim /etc/nginx/nginx.conf
http {
…
…
include include/deny_list.txt; #在http里面加入这条
}
2、创建文件:
touch /etc/nginx/include/deny_list.txt
3、编写脚本:
vim /mnt/auto_ddos.sh
#!/bin/bash
#获取access日志每分钟单个ip访问次数超过500次的ip,并将此ip加入iptables,24小时后解封
log_path=/alidata/weblogs/access/www.huaqiaobao.cn_access.log
nginx_config=/etc/nginx/nginx.conf
month=env LANG=en_US.UTF-8 date|awk '{print $2}'
date=date +%d/${month}/%Y:%H:%M
grep “${date}” ${log_path}|awk ‘{print $1}’|sort |uniq -c|sort -nr|grep -v 183.129.173.34 >/mnt/number_ip.txt
line=cat /mnt/number_ip.txt|wc -l
for line in seq $line
do
number_ip=sed -n ${line}p /mnt/number_ip.txt
number=sed -n ${line}p /mnt/number_ip.txt|awk '{print $1}'
ip=sed -n ${line}p /mnt/number_ip.txt|awk '{print $2}'
time_new=date +%s
if [ ${number} -gt 500 ];then
grep ${ip} /etc/nginx/include/deny_list.txt
if [ $? != 0 ];then
echo “deny ${ip};” >>/etc/nginx/include/deny_list.txt
/usr/sbin/nginx -t -c ${nginx_config}
if [ $? = 0 ];then
/usr/sbin/nginx -s reload
grep ${ip} /mnt/ip_ddos.txt
if [
?
!
=
0
]
;
t
h
e
n
e
c
h
o
"
? != 0 ];then echo "
?!=0];thenecho"{time_new} ${ip}" >>/mnt/ip_ddos.txt
fi
fi
fi
fi
done
#24小时后解封ip
line=cat /mnt/ip_ddos.txt|wc -l
for line in seq $line
do
time_old=sed -n ${line}p /mnt/ip_ddos.txt|awk '{print $1}'
time_new=date +%s
time_finish=echo $((time_new-time_old))
ip=sed -n ${line}p /mnt/ip_ddos.txt|awk '{print $2}'
if [ ${time_finish} -gt 86400 ];then
grep ${ip} /etc/nginx/include/deny_list.txt
if [
?
=
0
]
;
t
h
e
n
s
e
d
−
i
"
/
? = 0 ];then sed -i "/
?=0];thensed−i"/{ip}/d" /etc/nginx/include/deny_list.txt
/usr/sbin/nginx -t -c ${nginx_config}
if [
?
=
0
]
;
t
h
e
n
/
u
s
r
/
s
b
i
n
/
n
g
i
n
x
−
s
r
e
l
o
a
d
s
e
d
−
i
"
/
? = 0 ];then /usr/sbin/nginx -s reload sed -i "/
?=0];then/usr/sbin/nginx−sreloadsed−i"/{ip}/d" /mnt/ip_ddos.txt
fi
fi
fi
done
4、编写定时任务:
crontab -e
-
-
-
-
- sleep 58;sh /mnt/auto_ddos.sh
-
-
-