Skip to content

Instantly share code, notes, and snippets.

@elvisciotti
Last active August 14, 2022 06:38
Show Gist options
  • Save elvisciotti/73faf3d9a90b938c59a6139144ab0bb0 to your computer and use it in GitHub Desktop.
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
#!/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
@elvisciotti
Copy link
Author

#install
sudo su
apt-get install jq -y
wget -O /usr/local/bin/cloudflareSecurityLevel
chmod +x /usr/local/bin/cloudflareSecurityLevel

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment