设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 数据 手机
当前位置: 首页 > 教程 > 正文

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

发布时间:2022-06-19 14:26 所属栏目:61 来源:互联网
导读:对于小量的ddos攻击我们可以使用iptables来防止了,当然也可以使用智能的shell脚本来实现了,下面我们一起来看看Shell脚本分析Nginx日志抗小量ddos攻击的例子. 网站被ddos攻击,遂写了个脚本来抵抗一下,实现方式: 1.攻击特征,不同ip不断POST网站首页,造成资源消
  对于小量的ddos攻击我们可以使用iptables来防止了,当然也可以使用智能的shell脚本来实现了,下面我们一起来看看Shell脚本分析Nginx日志抗小量ddos攻击的例子.
 
  网站被ddos攻击,遂写了个脚本来抵抗一下,实现方式:
 
  1.攻击特征,不同ip不断POST网站首页,造成资源消耗过度.
 
  2.分析nginx访问日志,判断POST特征取得客户端访问ip.
 
  3.将连接数大于50的攻击ip封杀.
 
  4.记录攻击ip到文档.
 
  5.每次取得的攻击ip与已有攻击ip比较.
 
  查看源代码:
 
  #!/bin/bash
  
  WEBSITES=(
   example.com
  )
  
  minute_now=`date +%M`
  max_connections=50
  banips="/wwwdata/jobs/banips.txt"
  
  for site in ${WEBSITES[*]}
  do
   access_log_file="/wwwdata/logs/${site}.access.log"
   if [ -f "${access_log_file}" ]
   then
    cat ${access_log_file} | grep POST | awk '{print $1}' | sort |uniq -c| sort -nr > /wwwdata/jobs/ip_records.txt
     
    lines=`wc -l /wwwdata/jobs/ip_records.txt | awk '{print $1}'`
    echo "Lines: $lines"
     
    i=1
    while [ ${i} -le ${lines} ]
    do
     ip_record=`head -${i} /wwwdata/jobs/ip_records.txt | tail -1 | sed 's/^[ \t]*//g'`
      
     ip_count=`echo ${ip_record} | awk '{print $1}'`
     ip_address=`echo ${ip_record} | awk '{print $2}'`
      
     echo "${ip_count} ${ip_address}"
      
     if [ ${ip_count} -gt ${max_connections} ]
     then
      banned=`cat ${banips} | grep ${ip_address} | wc -l`
      if [ ${banned} -lt 1 ]
      then
       iptables -A INPUT -s x.x.x.x -p tcp -m state --state NEW -m tcp --dport 80 -j DROP
       echo ${ip_address} >> ${banips}
      fi
     fi
      
     i=`expr ${i} + 1`
    done
     
    service iptables save
    service iptables restart
     
    if [ ${minute_now} -eq 30 ]
    then
     cat ${access_log_file} >> /wwwdata/logs/olds/${site}.access.log
     cat /dev/null > ${access_log_file}
    fi --phpfensi.com
   fi
  done
  
  if [ ${minute_now} -eq 30 ]
  then
   service nginx restart
  fi。
 

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读