Linux系统防CC攻击自动拉黑IP增强版(Shell脚本)

这篇文章主要介绍了Linux系统防CC攻击自动拉黑IP增强版(Shell脚本),需要的朋友可以参考下
前天没事写了一个防CC攻击的Shell脚本,没想到这么快就要用上了,原因是因为360网站卫士的缓存黑名单突然无法过滤后台,导致WordPress无法登录!虽然,可以通过修改本地hosts文件来解决这个问题,但是还是想暂时取消CDN加速和防护来测试下服务器的性能优化及安全防护。

前天写的Shell脚本是加入到crontab计划任务执行的,每5分钟执行一次,今天实际测试了下,可还是可以用的,但是感觉5分钟时间有点过长,无法做到严密防护。于是稍微改进了下代码,现在简单的分享下!

一、Shell代码

#!/bin/bash#Author:ZhangGe#Desc:Auto Deny Black_IP Script.#Date:2014-11-05#取得参数$1为并发阈值,若留空则默认允许单IP最大100并发(实际测试发现,2M带宽,十来个并发服务器就已经无法访问了!)if [[ -z $1 ]];then num=50else num=$1fi#巧妙的进入到脚本工作目录cd $(cd $(dirname $BASH_SOURCE) && pwd)#请求检查、判断及拉黑主功能函数function check(){ iplist=netstat -an |grep ^tcp.*:80|egrep -v 'LISTEN|127.0.0.1'|awk -F"[ ]+|[:]" '{print $6}'|sort|uniq -c|sort -rn|awk -v str=$num '{if ($1>str){print $2}}' if [[ ! -z $iplist ]]; then >./iplist/black_ip.txt for black_ip in $iplist do #白名单过滤中已取消IP段的判断功能,可根据需要自行修改以下代码(请参考前天写的脚本) #exclude_ip=echo $black_ip | awk -F"." '{print $1"."$2"."$3}' #grep -q $exclude_ip ./white_ip.txt grep -q $black_ip ./white_ip.txt if [[ ? e q 0 ] ] ; t h e n e c h o &quot; ? -eq 0 ]];then echo &quot; black_ip (white_ip)" >>./black_ip.txt else echo $black_ip >>./black_ip.txt iptables -nL | grep $black_ip ||(iptables -I INPUT -s KaTeX parse error: Expected 'EOF', got '&' at position 18: …ack_ip -j DROP &̲ echo "black_ip date +%Y-%m-%H:%M:%S">>./iplist/denylog.txt & echo 1 >./sendmail) fi done #存在并发超过阈值的单IP就发送邮件 if [[ cat ./sendmail == 1 ]];then sendmsg;fi fi}#发邮件函数function sendmsg(){ netstat -nutlp | grep “sendmail” >/dev/null 2>&1 || /etc/init.d/sendmail start >/dev/null 2>&1 echo -e “From: 发邮件地址@qq.com\nTo:收邮件地址@qq.com\nSubject:Someone Attacking your system!!\nIts Ip is” >./message cat ./black_ip.txt >>./message /usr/sbin/sendmail -f 发邮件地址@qq.com -t 收邮件地址@qq.com -i <./message >./sendmail}#间隔10s无限循环检查函数while truedo check #每隔10s检查一次,时间可根据需要自定义 sleep 10done
二、执行脚本
将以上代码保存为deny_blackip.sh之后,使用如下命令后台执行脚本(后面的50表示并发数,可自行调整):VPS云主机

复制代码 代码如下:
nohup ./deny_blackip.sh 50 &

执行后会出现如下信息:

[root@Mars_Server iptables]# nohup ./deny_blackip.sh 50 & [1] 23630[root@Mars_Server iptables]# nohup: ignoring input and appending output to `nohup.out’
表示如果脚本产生输出信息,将会写入到nohup.out文件,可以看到当前目录已经生成了一个空的nohup.out:

猜你喜欢

转载自blog.csdn.net/weixin_44400506/article/details/89306443