Article directory
Once your firewall rule list swells to thousands of entries, manually deleting them is like counting grains of sand in the desert—time-consuming and painful.
At this point, automated scripts become a lifesaver.
Why are automatic cleanup rules needed?
When using Cloudflare as a CDN and WAF, we often configure IP Access Rules to block malicious requests.
These rules may include annotations such as "Blocked by AI B" , "Wordfence Sync" , or "Known attacker's IP address".
The number of rules will increase rapidly over time.
If not cleaned up, the rules in the console will pile up, affecting management efficiency.
To make matters worse, the Cloudflare console does not offer a "one-click batch delete by comment" feature.
This means you can only manually select and delete them one by one, which is extremely inefficient.
Solution
To solve this problem, we can use the Cloudflare REST API.
By calling firewall/access_rules/rules Interfaces and scripts can:
- Get paginationAll rules under the current domain.
- Matching commentsKeywords in the field.
- Automatically initiate a DELETE requestBatch cleanup target rules.
This method is not only efficient, but also avoids human error.

Preparatory work
Before you start writing the script, you need to prepare several key parameters.
1. API Token
Go to the Cloudflare API Tokens page to create a new token.
Permissions must be granted: Zone → Firewall Services → Edit.
2. Zone ID
Log in to the Cloudflare console, go to the Overview page of your domain , and you can find the 32-digit Zone ID on the right.
3. Install dependency libraries
Run in PowerShell or the terminal:
python -m pip install requests
This will allow you to install it. requests The library ensures that the script can call the API correctly.
Complete Python script
Below is a ready-to-use Python script.
Save as cloudflare_clean.pyReplace API_TOKEN 和 ZONE_ID Just fine.
import requests
API_TOKEN = "你的_API_TOKEN"
ZONE_ID = "你的_ZONE_ID"
TARGET_NOTE = "Blocked by AIB"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json",
}
def delete_matching_ip_rules_zone():
page = 1
deleted_count = 0
while True:
url = f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/firewall/access_rules/rules?page={page}&per_page=100"
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"请求失败: {response.text}")
break
data = response.json()
rules = data.get("result", [])
if not rules:
break
for rule in rules:
rule_id = rule.get("id")
rule_value = rule.get("configuration", {}).get("value")
rule_notes = rule.get("notes", "")
if TARGET_NOTE in rule_notes:
del_url = f"{url}/{rule_id}"
del_res = requests.delete(del_url, headers=headers)
if del_res.json().get("success"):
print(f"✅ 删除成功: {rule_value}")
deleted_count += 1
result_info = data.get("result_info", {})
total_pages = result_info.get("total_pages", 1)
if page >= total_pages:
break
page += 1
print(f"清理完成,共删除 {deleted_count} 条规则。")
if __name__ == "__main__":
delete_matching_ip_rules_zone()
run script
Enter the following in the terminal:
python /path/to/cloudflare_clean.py
The script will automatically scan for and delete rules with specified comments.
Frequently Asked Questions and Troubleshooting Guide
1. Zone vs Account Permissions
- Zone level rules: apply only to a single domain.
- Account-level rules: Apply to the entire account; require modification of the API path.
/accounts/{ACCOUNT_ID}/....
2. Authentication error reporting
If it appears 403 Authentication errorThis is usually due to an incorrect permission scope setting.
Ensure that the Token permission includes Firewall Services → Edit.
3. Pagination mechanism
The Cloudflare API returns a maximum of 100 rules at a time.
The script passes result_info.total_pages Automatic page turning ensures a complete scan.
Why Automation is an Inevitable Choice
In a real production environment, the number of rules can easily exceed 5000.
Manual deletion is not only time-consuming, but also prone to omissions.
With automation scripts, you can:
- Expired rules are cleared daily.
- Keep your firewall rule list clean.
- To avoid mistakenly banning legitimate users.
This approach makes website security management more efficient.
The official Cloudflare documentation clearly states:
"The API provides programmatic access to manage firewall rules, including creation, listing, and deletion."
来源:Cloudflare API Documentation
This indicates that the official API has been provided, but the batch deletion function has not been implemented in the console.
Conclusion
In the world of information security, efficiency is defense.
By calling the Cloudflare API through Python scripts, we not only overcame the limitations of the console, but also ushered in an era of automation for firewall rule management.
This is a combination of technology and wisdom , and an inevitable trend in website security operations.
True masters don't spend their days clicking the mouse in the console; they use code to make machines do the tedious work for them.
So let's take action.
Make your firewall rules function like a precise clock, not a jumble of messy digital garbage.
The essence of security is order. And behind order lies automation.
Hopefully, the article "How to Automatically Batch Clean Up IP Access Rules with Specified Comments in WAF Using Cloudflare API + Python" shared on Chen Weiliang's blog ( https://www.chenweiliang.com/ ) will be helpful to you.
Feel free to share this article's link: https://www.chenweiliang.com/cwl-34436.html
