Cloudflare API- bash script to block IP address in firewall (check if IP exists)

Cloudflare API- bash script to block IP address in firewall 
[ check if IP exists in the firewall before blocking ]

Note: The details of organization,zone etc can be found in respective cloudflare login

Requirement: Install jq, https://stedolan.github.io/jq/

 

#!/bin/bash
organization=””
zones=””
email=””
authkey=””
id=””
org_name=””
notes=””

> ipsblocked.txt

for i in `cat ips.txt`; do
RESULT_JSON=`curl -sSX GET “https://api.cloudflare.com/client/v4/organizations/$organization/firewall/access_rules/rules?mode=block&configuration_target=ip&configuration_value=$i” -H “X-Auth-Email: $email” -H “X-Auth-Key: $authkey” -H “Content-Type: application/json”;`
echo “\n”
#echo “$RESULT_JSON”
#echo ” result with jq”
STATUS_IPBLOCKED=`echo “$RESULT_JSON” | jq ‘.mode’`

if [ $STATUS_IPBLOCKED != block ]
then
curl -sSX POST “https://api.cloudflare.com/client/v4/organizations/$organization/firewall/access_rules/rules” -H “X-Auth-Email: $email” -H “X-Auth-Key: $authkey” -H “Content-Type: application/json” –data “{\”mode\”:\”block\”,\”scope\”:{\”id\”:\”$id\”,\”name\”:\”$org_name\”,\”type\”:\”organization\”},\”configuration\”:{\”target\”:\”ip\”,\”value\”:\”$i\”},\”notes\”:\”$notes\”}” ;
echo “\n”
echo “IP $i blocked in Cloudflare”
echo “IP $i blocked in Cloudflare” >> ipsblocked.txt
echo “\n”
else
echo “IP $i already blocked in Cloudflare, skip”
echo “IP $i already blocked in Cloudflare, skip” >> ips_blocked.txt
fi

echo “\n”
done

2 thoughts on “Cloudflare API- bash script to block IP address in firewall (check if IP exists)”

Leave a Reply

Your email address will not be published. Required fields are marked *