参考文章:
http://blog.csdn.net/samxx8/article/details/46897237
注意:本人在生产环境中遭遇到cc攻击,连接数过多,cpu负载过大,结果导致服务不可用!
shell脚本
#!/bin/bash
#取得参数$1为并发阈值,若留空则默认允许单IP最大50并发
if [[ -z $1 ]];then
num=50
else
num=$1
fi
cd /server/scripts/
check() {
iplist=`netstat -an | grep ^tcp.*:8086 | egrep -v 'LISTEN|127.0.0.1|192.168.0.15' | awk -F '[ ]+' '{print $5}' | awk -F ':' '{print $4}' | sort | uniq -c|sort -rn |awk -v str=$num '{if ($1>str){print $2}}' `
if [[ ! -z $iplist ]];
then
>./black_ip.txt
for black_ip in $iplist
do
grep -q $black_ip ./white_ip.txt
if [[ $? -eq 0 ]];then
echo "$black_ip (white_ip)" >>./black_ip.txt
else
echo $black_ip >>./black_ip.txt
iptables -nL | grep $black_ip ||(iptables -I INPUT -s $black_ip -j DROP & echo "$black_ip `date +%Y-%m-%H:%M:%S`">>./deny.log & echo 1 > ./sendmail)
fi
done
# 存在并发超过阈值的单IP就发送邮件
if [[ `cat ./sendmail` == 1 ]];then sendmsg;fi
fi
}
#发邮件函数
function sendmsg(){
echo -e "From: auto@xxxx.com\nTo:auto@xxxx.com\nSubject:Someone Attacking your system!!\nIts Ip is" >./message
cat ./black_ip.txt >>./message
mail -s "blackip" auto@xxxx <./message
>./sendmail
}
while true
do
check
#每隔10s检查一次,时间可根据需要自定义
sleep 10
done
注意:脚本按需修改哦
后台运行
nohup bash /server/scripts/cc.sh &