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。
-
#!/bin/bash # FILES: nginx的access.log文件 FILES="/data/nginx/logs/access.log" # sensitive: 敏感关键字 sensitive="sensitive_word" # threshold: 一分钟内请求频率阈值 threshold=1000 ip_file="/tmp/ip_file" sensitive_file="/tmp/sensitive_file" DATE=`date -d '1 minutes ago' +%Y:%H:%M` grep ${DATE} ${FILES} | awk '{print $1}' | sort | uniq -c | sort -n | tail -n 1 > ${ip_file} grep ${DATE} ${FILES} | grep -i ${sensitive} | awk '{print $1}' | sort -n | uniq > ${sensitive_file} ip_file_number=`awk '{print $1}' ${ip_file}` ip_file_ip=`awk '{print $2}' ${ip_file}` if [[ $ip_file_number -gt $threshold ]];then ipset add blacklist ${ip_file_ip} timeout 3600 fi if [ -s ${sensitive_file} ];then for sensitive_ip in `cat ${sensitive_file}` do ipset add blacklist ${sensitive_ip} done fi
py脚本
-
#!/usr/bin/env python # -*- coding: utf-8 -*- # import os import time threshold = 120 # 获取前一分钟的结果 date = time.strftime('%Y:%H:%M', time.localtime(time.time()-60)) filename = '/usr/share/nginx/logs/geokon.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 将被禁止访问' % (threshold, ipaddr)) popen('ipset add blacklist %s timeout 3600 &>/dev/null' % (ipaddr)) elif num >= 50: 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 地址