網站被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