当前位置:首页 > linux教程 > 列表

linux下Shell脚本分析Nginx日志抗小量ddos攻击

发布:smiling 来源: PHP粉丝网  添加日期:2015-04-21 13:38:14 浏览: 评论:0 

对于小量的ddos攻击我们可以使用iptables来防止了,当然也可以使用智能的shell脚本来实现了,下面我们一起来看看Shell脚本分析Nginx日志抗小量ddos攻击的例子.

网站被ddos攻击,遂写了个脚本来抵抗一下,实现方式:

1.攻击特征,不同ip不断POST网站首页,造成资源消耗过度.

2.分析nginx访问日志,判断POST特征取得客户端访问ip.

3.将连接数大于50的攻击ip封杀.

4.记录攻击ip到文档.

5.每次取得的攻击ip与已有攻击ip比较.

查看源代码:

  1. #!/bin/bash 
  2.  
  3. WEBSITES=( 
  4.  example.com 
  5. ) 
  6.  
  7. minute_now=`date +%M` 
  8. max_connections=50 
  9. banips="/wwwdata/jobs/banips.txt" 
  10.  
  11. for site in ${WEBSITES[*]} 
  12. do 
  13.  access_log_file="/wwwdata/logs/${site}.access.log" 
  14.  if [ -f "${access_log_file}" ] 
  15.  then 
  16.   cat ${access_log_file} | grep POST | awk '{print $1}' | sort |uniq -c| sort -nr > /wwwdata/jobs/ip_records.txt 
  17.    
  18.   lines=`wc -l /wwwdata/jobs/ip_records.txt | awk '{print $1}'` 
  19.   echo "Lines: $lines" 
  20.    
  21.   i=1 
  22.   while [ ${i} -le ${lines} ] 
  23.   do 
  24.    ip_record=`head -${i} /wwwdata/jobs/ip_records.txt | tail -1 | sed 's/^[ \t]*//g'` 
  25.     
  26.    ip_count=`echo ${ip_record} | awk '{print $1}'` 
  27.    ip_address=`echo ${ip_record} | awk '{print $2}'` 
  28.     
  29.    echo "${ip_count} ${ip_address}" 
  30.     
  31.    if [ ${ip_count} -gt ${max_connections} ] 
  32.    then 
  33.     banned=`cat ${banips} | grep ${ip_address} | wc -l` 
  34.     if [ ${banned} -lt 1 ] 
  35.     then 
  36.      iptables -A INPUT -s x.x.x.x -p tcp -m state --state NEW -m tcp --dport 80 -j DROP 
  37.      echo ${ip_address} >> ${banips} 
  38.     fi 
  39.    fi 
  40.     
  41.    i=`expr ${i} + 1` 
  42.   done 
  43.    
  44.   service iptables save 
  45.   service iptables restart 
  46.    
  47.   if [ ${minute_now} -eq 30 ] 
  48.   then 
  49.    cat ${access_log_file} >> /wwwdata/logs/olds/${site}.access.log 
  50.    cat /dev/null > ${access_log_file} 
  51.   fi --phpfensi.com 
  52.  fi 
  53. done 
  54.  
  55. if [ ${minute_now} -eq 30 ] 
  56. then 
  57.  service nginx restart 
  58. fi

Tags: linux脚本 Shell脚本 Nginx日志

分享到: