如果我們的網站遭遇 CC 和 DDoS 攻擊時,我們可以用這個方法來簡單的防禦。可以根據系統的負載狀態通過CloudflareAPI實現自動開啟5秒盾。
操作步驟
當伺服器受到攻擊時,系統負載就會爆增,利用腳本自動檢測系統負載,當壓力超過一定的值時就可以切換為“ I'm Under Attack!“模式了。
#下載
cd /root && git clone https://github.com/Machou/Cloudflare-Block.git DDoS
#打开Cloudflare.sh,修改配置
API_KEY You're Global API Key (https://dash.cloudflare.com/profile)
MAIL_ACCOUNT Email of your Cloudflare account
DOMAIN Zone ID (https://dash.cloudflare.com/_zone-id_/domain.com)
#設置定時任務
crontab -e
*/1 * * * * /root/DDoS/Cloudflare.sh 0 # check every 1 minute if protection is not enabled
*/20 * * * * /root/DDoS/Cloudflare.sh 1 # check every 20 minutes if prot
完整原始程式碼
腳本預設的是檢測系統負載為 10,啟動“ I'm Under Attack!“模式,你以根據需要來調整。文稿如下:
#!/bin/bash
# $1 = 1min, $2 = 5min, $3 = 15min
loadavg=$(cat /proc/loadavg|awk '{printf "%f", $1}')
# load is 10, you can modify this if you want load more than 10
maxload=10
# Configuration API Cloudflare
# You're Global API Key (https://dash.cloudflare.com/profile)
api_key=
# Email of your account Cloudflare
email=
# Zone ID (https://dash.cloudflare.com/_zone-id_/domain.com)
zone_id=
# create file attacking if doesn't exist
if [ ! -e $attacking ]; then
echo 0 > $attacking
fi
attacking=./attacking
hasattack=$(cat $attacking)
if [ $(echo "$loadavg > $maxload"|bc) -eq 1 ]; then
if [[ $hasattack = 0 && $1 = 0 ]]; then
# Active protection
echo 1 > $attacking
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$zone_id/settings/security_level" \
-H "X-Auth-Email: $email" \
-H "X-Auth-Key: $api_key" \
-H "Content-Type: application/json" \
--data '{"value":"under_attack"}'
fi
else
if [[ $hasattack = 1 && $1 = 1 ]]; then
# Disable Protection
echo 0 > $attacking
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$zone_id/settings/security_level" \
-H "X-Auth-Email: $email" \
-H "X-Auth-Key: $api_key" \
-H "Content-Type: application/json" \
--data '{"value":"high"}'
fi
fi
exit 0
寶塔面板計劃任務
我們如果想省點事就直接複製上面第一條中的腳本代碼,放在計劃任務的shell腳本之中,也可以是同樣的效果。

- 問題解決
bc: command not found
yum -y install bc
- /attacking 檔不存在
把腳本代碼中 26 行的 attacking=./attacking 剪切到 20 行
文章標題:檢測到CC攻擊自動開啟cloudflare5秒盾
本文鏈接:https://angelal.cc/1234.html
文章版權:除非特別註明,否則均為AngelaL的原創文章,轉載必須以鏈接形式標明本文鏈接
本文最後更新發佈於:2025年02月26日 21:36, 某些文章具有時效性,若有錯誤或已失效,請在下方留言。