Last active
August 14, 2022 06:38
-
-
Save elvisciotti/73faf3d9a90b938c59a6139144ab0bb0 to your computer and use it in GitHub Desktop.
Bash script to change Cloudflare security level via RESTful API. Could be used in a cronjob to disable the website during high load
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Toggles cloudflare security_settings base on system load | |
# Only prints output when the setting is changed to a different one | |
# Needs "jq" installed | |
# | |
# e.g. essentially_off, low, medium, high, under_attack | |
USERNAME=$1 | |
AUTHKEY=$2 | |
ZONEID=$3 | |
DESIRED_VALUE=$4 | |
RULE=$5 | |
# calculate vars | |
CURRENT_LOAD=$(uptime | awk '{print $10+0}') | |
BC=$(echo "$CURRENT_LOAD $RULE" | bc) | |
if [ "$BC" = "1" ]; then | |
CURRENT_VALUE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${ZONEID}/settings/security_level" \ | |
-H "X-Auth-Email: ${USERNAME}" \ | |
-H "X-Auth-Key: ${AUTHKEY}" \ | |
-H "Content-Type: application/json" | jq -r '.result.value') | |
if [ $CURRENT_VALUE != $DESIRED_VALUE ]; then | |
curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/${ZONEID}/settings/security_level" \ | |
-H "X-Auth-Email: ${USERNAME}" \ | |
-H "X-Auth-Key: ${AUTHKEY}" \ | |
-H "Content-Type: application/json" \ | |
--data "{\"value\":\"$DESIRED_VALUE\"}" | |
echo "Load = $CURRENT_LOAD, cloudflare = $CURRENT_VALUE, toggled to $DESIRED_VALUE" | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#install
sudo su
apt-get install jq -y
wget -O /usr/local/bin/cloudflareSecurityLevel
chmod +x /usr/local/bin/cloudflareSecurityLevel