A Python script to add, delete, or list IP addresses in a Cloudflare Custom IP List using the Cloudflare API. This is particularly useful when integrated with Fail2Ban as a custom action to dynamically manage malicious IPs from remote client's access through clouflares proxy service.
- Add or delete IPs to/from a specific Cloudflare list (e.g.,
block,challenge,bots) - View the current list contents
- Supports optional comments
- Can be integrated with Fail2Ban for automated IP blocking
To use this tool effectively, the following setup is required:
- Cloudflare Proxy Enabled – Your domain must be proxied through Cloudflare (orange cloud enabled).
- Origin Firewall Rules – Your origin server’s firewall must be configured to allow only Cloudflare IPs and block all direct traffic.
- Pre-Created IP List – You must have already created one or more Cloudflare IP Lists under Account → Configurations → Lists.
- Associated Firewall Rules – You must have firewall rules configured to act on these lists. For example, you can block or challenge IPs that are on a specific list when they access your site via Cloudflare.
- Cloudflare Lists – These are account wide with CF and even the free accounts can create custom lists limit
You will also need:
- Python 3.x
requestsmodule (pip install requests)- A Cloudflare API token with permission to manage Lists
- Your Cloudflare Account ID and Zone ID
Edit the USER-SPECIFIC SETTINGS section in the script to define:
CF_API_TOKEN = 'your_api_token'
CF_ACCOUNT_ID = 'your_account_id'
CF_ZONE_ID = 'your_zone_id'
LIST_IDS = {
'block': 'your_block_list_id',
'challenge': 'your_challenge_list_id',
'bots': 'your_bots_list_id'
}Make the script executable:
chmod +x modifyBanList.pyThen run:
./modifyBanList.py <ip> addExample:
./modifyBanList.py 203.0.113.4 add./modifyBanList.py <ip> add --comment "Port scan detected"./modifyBanList.py <ip> add --list-name bots./modifyBanList.py <ip> del./modifyBanList.py <ip> del --list-name challenge./modifyBanList.py --list --list-name blockCreate a custom action file:
/etc/fail2ban/action.d/cloudflarelist.conf
[Definition]
actionstart =
actionstop =
actioncheck =
actionban = /path/to/modifyBanList.py <ip> add --comment "Banned by Fail2Ban"
actionunban = /path/to/modifyBanList.py <ip> del
[Init]Replace /path/to/modifyBanList.py with the actual full path.
Then in your jail config (e.g., /etc/fail2ban/jail.d/nginx-bots.conf):
[nginx-bots]
enabled = true
filter = nginx-bad-bots
action = cloudflarelist
logpath = /var/log/nginx/access.log
findtime = 600
bantime = 3600
maxretry = 5Run with --debug to print more verbose output:
./modifyBanList.py <ip> add --debugMIT