nginx+iptables+ipset 封禁频繁访问web服务的恶意IP
转载来源–> https://blog.csdn.net/qq_36698956/article/details/90447648 iptables直接针对ip进行封禁,在ip数量不大的时候是没什么问题的,但当有大量ip的时候性能会严重下降,iptables是O(N)的性能。而ipset就像一个集合,把需要封闭的ip地址写入这个集合中,ipset 是O(1)的性能,可以有效解决iptables直接封禁大量IP的性能问题。
如果是RedHat/CentOS,首先用yum(Ubuntu/Debian用将yum换为apt-get既可 )安装ipset。
yum install ipset -y
ipset创建基于ip hash的集合名称,例如blacklist,timeout 3600 表示封禁3600s; iptables开启封禁80,443策略
ipset create blacklist hash:ip timeout 3600 # 当然也可以不加timeout 3600 ,也可以只写ipset create blacklist hash:ip , blacklist 为集合名称,可随意, 不加就是长期封闭 iptables -A INPUT -p tcp -m set --match-set blacklist src -m multiport --dports 443,80 -j DROP # 封禁黑名单IP的所有请求 iptables -I INPUT -p tcp -m set --match-set blacklist src -m multiport -j DROP # iptables v1.4.7: multiport expection an option # 如果报上面的错误,需要按如下写 -A INPUT -p tcp -m multiport --destination-port 443,80 -m set --match-set blocklist src -j DROP基于自定义访问频率阈值或者请求敏感关键字来创建自动筛选恶意IP的脚本/data/iptables_ipset_deny.sh。
py脚本
#!/usr/bin/env python # -*- coding: utf-8 -*- # import os import time threshold = 120 # 获取前1分钟的时间 date=time.strftime('%Y:%H:%M', time.localtime(time.time()-60)) # date = time.strftime('%Y:%H:%M') filename = '/usr/share/nginx/logs/xx.access.log ' def popen(command): return os.popen(command).readlines() def main(): with open('/tmp/ipset.txt', 'a') as f: f.write('%s: 日志搜索...........\n' % (date)) command = "grep %s %s | awk '{counts[$1]++}; END {for(url in counts) print counts[url], url}'" % (date, filename) for ip in popen(command): num, ipaddr = ip.split(' ') num, ipaddr = int(num), ipaddr.strip() # 第一个值是整型, 第二个值应当去掉空格 if num >= threshold: if all(popen('ipset list | grep %s' % (ipaddr))): # 如果不为true 那就添加 f.write('每分钟大于%s次 地址: %s 将被禁止访问\n' % (threshold, ipaddr)) os.system('/usr/sbin/ipset add blacklist %s &>/dev/null' %(ipaddr)) # popen('ipset add blacklist %s' % (ipaddr)) elif num >= 10: f.write('访问次数 %s: %s\n' % (num, ipaddr)) f.write('日志搜索结束.................\n\n\n') if __name__ == '__main__': main()用crontab定时启动脚本。
echo "* * * * * bash /data/iptables_ipset_deny.sh" >> /etc/crontab # 当然也可以配置crontab一分钟执行一次定时任务: */1 * * * * bash /data/iptables_ipset_deny.sh查看black地址
ipset list 删除地址 ~]# ipset del ipsetname 地址