利用shell脚本拒绝TCP连接数大于20的IP,shelltcp


最近服务器频繁遭到CC攻击,抓包、分析连接数后,发现单台服务器的并发连接数达到5万多,本想利用iptables的connlimit模块对连接数据进行限制的,无奈我接手的这几台服务器都没打此补丁,决定利用shell脚本对于一些连接数过大的IP进行屏蔽

vi /opt/drop_tcp.sh

#!/bin/sh


netstat-nat -n > /opt/netstat-net.log


file=/opt/drop_ip.log


//判断连接数大于20的IP


/bin/awk -F: '/tcp/{a[$(NF-2)]++}END{for(i in a)if(a[i]>20)print i}' /opt/netstat-net.log > $file


drop_ip=`cat $file |awk '{print $2}'`


for iptables_ip in $drop_ip


do


//如果iptables的PREROUTING链中,没有出现过这个IP,则直接用iptables丢弃所有来自这个IP地址发送的请求


if [ $iptables_ip != $0 ] && [ -z "` iptables -nvL -t nat|grep $iptables_ip`" ];then


/sbin/iptables -t nat -I PREROUTING -s $iptables_ip -j DROP


fi


done

//定期执行此脚本

crontab -e

*/5 * * * * sh /opt/drop_tcp.sh

这样对于单IP连接数超过20的进行屏蔽

为了避免iptables规则过于臃肿,也要对已经屏蔽IP进行解封

vi /opt/drop_iptables.sh

#!/bin/sh


iptables=/opt/iptables.log


iptables-save > $iptables


drop_ip1=`cat $iptables |awk /DROP/'{print $4}'`


for iptables_ip1 in $drop_ip1


do


/sbin/iptables -t nat -D PREROUTING -s $iptables_ip1 -j DROP


done

//定期执行此脚本

crontab -e

* */3 * * * sh /opt/drop_iptables.sh

相关内容

    暂无相关文章