近期發現大量高併發爬蟲瘋狂抓取我們網站的部分介面,導致頻寬異常和服務不穩定。為了暫時緩解壓力,決定編寫一個腳本自動封禁這些異常 IP。
經過日誌排查發現,這些爬蟲 IP 數量不多,但單 IP 併發極高,基本維持在 10-20 併發之間。正常用戶單 IP 幾乎很少超過 10 併發。因此處理邏輯很明確:
iptables 臨時封禁異常 IP為了便於管理,採用 Shell + crontab 方式實現。以下是核心腳本代碼:
#!/bin/sh
## Author: bbzsxjj
## Email: bbzsxjj@163.com
## Usage: auto deny ip by iptables
## Ver: 1.0
timenow=`date +'%H%M00'`
timelast=`date +'%H%M00' -d '-5min'`
lastnum=1000000 ## 日誌行數,可根據業務頻率調整
limitnum=3000 ## 併發限制:300*10
ipbin=/sbin/iptables
NeedDenyiplist=/opt/sbin/ipdeny.list
NeedPurgeiplist=/opt/sbin/ippurge.list
LogFile=/data/logs/haproxy.log
CreateList(){
if [ -f ${LogFile} ]; then
if [ -f ${NeedDenyiplist} ]; then
mv ${NeedDenyiplist} ${NeedPurgeiplist}
fi
# 根據日誌格式提取異常 IP,需根據實際日誌格式調整 awk 處理邏輯
tail -n${lastnum} ${LogFile} | awk '{gsub(/:/,"",$3); if($3>='${timelast}' && $3<='${timenow}'){a[$6]++}} END {for(i in a){if(a[i]>'${limitnum}'){print $6}}}' >> ${NeedDenyiplist}
if [ `wc -l ${NeedDenyiplist} | awk '{print $1}'` -eq 0 ]; then
rm -rf ${NeedDenyiplist}
fi
fi
}
DenyIP(){
for Dip in `cat ${NeedDenyiplist} | grep -E -v '^$|#'`; do
${ipbin} -I INPUT -s ${Dip} -p tcp --dport 80 -j DROP
done
}
PurgeIP(){
for Dip in `cat ${NeedPurgeiplist} | grep -E -v '^$|#'`; do
${ipbin} -D INPUT -s ${Dip} -p tcp --dport 80 -j DROP
done
}
main(){
CreateList
if [ -f ${NeedPurgeiplist} ]; then
PurgeIP
fi
if [ -f ${NeedDenyiplist} ]; then
DenyIP
fi
}
main
將腳本加入 crontab,每 5 分鐘執行一次:
### denyip
*/5 * * * * /bin/sh /opt/sbin/denyip.sh >/dev/null 2>&1;
awk 處理部分需根據實際 HAProxy 日誌格式調整字段提取邏輯($3 為時間,$6 為客戶端 IP)lastnum 限制讀取日誌行數,避免全量掃描影響性能這個腳本作為緊急防護手段相當實用,但在生產環境長期使用建議結合更完善的 WAF 或流量分析系統。