欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

nginx/iptables动态IP黑白名单实现方案

程序员文章站 2022-06-03 21:17:04
...

nginx/iptables动态IP黑白名单实现方案

一、手动封IP步骤

1.Nginx手动封IP

1.获取各个IP访问次数
awk '{print $1}' nginx.access.log |sort |uniq -c|sort -n
2.新建一个黑名单文件 blacklist.conf ,放在 nginx/conf下面
3.添加一个IP ,deny 192.168.59.1;
4.在http或者server模块引入
include blacklist.conf ;
5.需要重启服务器, nginx -s reload; 即可生效

2.iptables手动封IP

单个IP的命令是
iptables -I INPUT -s 124.115.0.199 -j DROP

封IP段的命令是
iptables -I INPUT -s 124.115.0.0/16 -j DROP

封整个段的命令是
iptables -I INPUT -s 194.42.0.0/8 -j DROP

封几个段的命令是
iptables -I INPUT -s 61.37.80.0/24 -j DROP
iptables -I INPUT -s 61.37.81.0/24 -j DROP 

解封
iptables -F
清空
iptables -D INPUT 数字


service iptables save
service iptables restart
iptables -L -n

二、Nginx自动封IP

1.示例:覆盖

#!/bin/sh
tail -n500000 /usr/local/tengine/logs/access.log |awk '{print $1,$7}' |grep -i -E "payments|smsSdk|reportErrorLog|errorPay" |awk '{print $1}'|sort|uniq -c |sort -rn |awk '{if($1>100)print "deny "$2";"}' > /usr/local/tengine/conf/ip.blacklist.auto.conf
/usr/local/tengine/sbin/nginx -s reload

2.示例:追加

#!/bin/sh
cat /usr/local/tengine/logs/access.log |awk '{print $1,$7}' |grep -i -E "payments|smsSdk|reportErrorLog|errorPay" |awk '{print $1}'|sort|uniq -c |sort -rn |awk '{if($1>500)print "deny "$2";"}' >> /usr/local/tengine/conf/ip.blacklist.auto.append.conf
/usr/local/tengine/sbin/nginx -s reload

这里注意 >是覆盖,>>是追加

3.nginx中配置

location / {
    
    ...
    limit_req zone=one burst=5 nodelay;

    include ip.blacklist.auto.append.conf;
    include ip.blacklist.auto.conf;
        
}

三、添加到系统计划任务

crontab每隔10分钟执行一次

crontab -e
*/10 * * * * /data/scripts/nginx_ipblack_auto.sh
或者:
0,10,20,30,40,50 /data/scripts/nginx_ipblack_auto.sh

四、iptables自动封IP

 
#!/bin/bash
num=100 #上限
list=`netstat -an |grep ^tcp.*:80|egrep -v 'LISTEN|127.0.0.1'|awk -F"[ ]+|[:]" '{print $6}'|sort|uniq -c|sort -rn|awk '{if ($1>$num){print $2}}'`
for i in $list
do
      iptables -I INPUT -s $i --dport 80 -j DROP
done

五、tengine限流模块

tengine 限制同IP对同URL连接数限制的配置

 white_black_list_conf conf/white.list zone=white1:4m;
 white_black_list_conf conf/black.list zone=black1:4m;


limit_req_zone $binary_remote_addr zone=one:3m rate=1r/s;
limit_req_zone $binary_remote_addr $uri zone=two:3m rate=1r/s;
limit_req_zone $binary_remote_addr $request_uri zone=thre:3m rate=1r/s;