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

  最近服务器频繁遭到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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值