网站被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 fi done if [ ${minute_now} -eq 30 ] then service nginx restart fi (责任编辑:IT) |