Linux简单处理CC攻击shell脚本

第一个脚本是通过查找日志中访问次数过多的ip,并用iptables屏蔽,600秒解封。

  1. #!/bin/bash
  2. btime=600
  3. attacks=20
  4. tmpBlockIPFile=/home/tmp_block_ip
  5. timestamp=$(date +%s)
  6. logPath="/home/ban.log"
  7.  
  8. #start detect bad ip
  9. badip=`tac /home/www.centos.bz/access.log  | awk '
  10. BEGIN{
  11. cmd="date -d \"1 minute ago\" +%H%M%S"
  12. cmd|getline a
  13. }
  14. {
  15. $4 = substr($4,14,8)
  16. gsub(":","",$4)
  17. $4=$4+0
  18. a=a+0
  19. if ($4>=a){
  20. print $1,$7
  21. } else {
  22. exit;
  23. }
  24. }' | egrep -v '\.(gif|jpg|jpeg|png|css|js)' | awk '{print $1}' | sort | uniq -c | awk -v '{$1=$1+0;t=t+0;if ($1>=t) print $2}'`
  25.  
  26. if [ ! -z "$badip" ];then
  27.     for ip in $badip;
  28.     do
  29.         if test -z "`/sbin/iptables -nL | grep $ip`";then
  30.             /sbin/iptables -I INPUT -s $ip -j DROP
  31.  
  32.             #record blocked ip
  33.             echo "$timestamp $ip" >> $tmpBlockIPFile
  34.             echo "$(date) $ip" >> $logPath
  35.         fi
  36.     done
  37. fi
  38.  
  39. #unblock ip
  40. if [ -f "$tmpBlockIPFile" ];then
  41.     ips=""
  42.     while read blockTime ip
  43.     do
  44.         ((interval=$timestamp - $blockTime))
  45.         if [ $interval -gt $btime ];then
  46.           
  47.         fi   
  48.     done < $tmpBlockIPFile
  49.  
  50.     if [ "$ips" != "" ];then
  51.         for ip in `echo -e $ips`
  52.         do
  53.             sed -i "/$ip/d" $tmpBlockIPFile
  54.             /sbin/iptables -D INPUT -s $ip -j DROP
  55.         done
  56.     fi
  57. fi

将此代码保存为ban.sh,加入cronjob使每分钟执行一次。
此脚本的作用是:利用iptables屏蔽每分钟访问页面超过20的IP,这些页面已经排除图片,css,js等静态文件。
第二个脚本是通过在日志中查找cc攻击的特征进行屏蔽。

  1. #!/bin/bash
  2. keyword="cc-atack"
  3. badip=`tail -n 5000  /home/www.centos.bz/log/access.log | grep "$keyword"  | awk '{print $1}' | sort | uniq -c | sort -nr | awk '{print $2}'`
  4. if [ ! -z "$badip" ];then
  5. for ip in $badip;
  6. do
  7. if test -z "`/sbin/iptables -nL | grep $ip`";then
  8. /sbin/iptables -I INPUT -s $ip -j DROP
  9. fi
  10. done
  11. fi

keyword则是日志中cc的特征,替换成有效的即可。

标签:ShellLinux 发布于:2019-11-23 09:34:37