色戒 多的就不做介绍了,您会明白的!

检测到CC攻击自动开启cloudflare5秒盾

⚠️ 本文最后更新于2024年07月09日,已经过了135天没有更新,若内容或图片失效,请留言反馈

如果我们的网站遭遇 CC 和 DDoS 攻击时,我们可以用这个方法来简单的防御。可以根据系统的负载状态通过CloudflareAPI实现自动开启5秒盾。
项目地址

    https://github.com/Machou/Cloudflare-Bloc

操作步骤
当服务器受到攻击时,系统负载就会爆增,利用脚本自动检测系统负载,当压力超过一定的值时就可以切换为” 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 行

By 懒人 On