Linux 系統的 Shell 腳本功能強大,可用於自動化執行各類命令。當網站遭受小規模 DDoS 攻擊時,我們可以透過撰寫 Shell 腳本分析 Nginx 存取日誌,識別並封鎖異常 IP,從而達到防禦目的。本文將詳細介紹如何實作這套防禦機制。
典型的小規模 DDoS 攻擊特徵為:大量不同 IP 不斷對網站首頁發送 POST 請求,導致伺服器資源過度消耗,服務變慢甚至癱瘓。
#!/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 ${ip_address} -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
將此腳本加入 crontab 定時執行(如每分鐘一次),即可自動偵測並封鎖異常流量。需注意:此方案僅適用於小規模攻擊,大規模 DDoS 仍需專業防護設備或雲端清洗服務。
