熱評
加載中...
當前位置:首頁技術館建站教學服務器檢測到CC攻擊自動開啟cloudflare5秒盾

檢測到CC攻擊自動開啟cloudflare5秒盾

如果我們的網站遭遇 CC 和 DDoS 攻擊時,我們可以用這個方法來簡單的防禦。可以根據系統的負載狀態通過CloudflareAPI實現自動開啟5秒盾。

操作步驟

當伺服器受到攻擊時,系統負載就會爆增,利用腳本自動檢測系統負載,當壓力超過一定的值時就可以切換為“ I'm Under Attack!“模式了。

nginx
#下載
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!“模式,你以根據需要來調整。文稿如下:

nginx
#!/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腳本之中,也可以是同樣的效果。

檢測到CC攻擊自動開啟cloudflare5秒盾
  1. 問題解決

bc: command not found

nginx
yum -y install bc
  1. /attacking 檔不存在
    把腳本代碼中 26 行的 attacking=./attacking 剪切到 20 行
AngelaL博客

       本文是原創文章,採用CC BY-NC-SA 4.0協議,完整轉載請註明來自AngelaL博客

給TA打賞
共{{data.count}}人
人已打賞
二開美化服務器

WP-Cron 優化指南:提升 WordPress 性能,減少伺服器負擔

2025-2-25 19:37:49

服務器

nginx的獲取ip的網頁

2025-2-26 21:39:49

0 條回复 A文章作者 M管理员
    
    暫無討論,說說你的看法吧
個人中心
購物車
優惠劵
今日簽到
有新私信 私信列表
搜索