This page looks best with JavaScript enabled

CLOUDFLARE API with Python

 ·  🎃 kr0m

In this article, we will learn how to use the Cloudflare API from a Python script, so we will be able to automate many administrative tasks. As an example, we will query the DNS records of the zones of several accounts. The library we will use is the official one: https://github.com/cloudflare/python-cloudflare

We create an access token:
https://www.cloudflare.com/a/account/my-account

We click on the API Tokens tab:

Create token:

We can use a generic access template or we can create a custom access:

We create a custom one so that it can only read DNS information:

It shows us a summary and we click on Create token:

We can manually check the token using curl:

curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY" \
-H "Content-Type:application/json"
{"result":{"id":"1f2e9ecf45463f956e02f6a4f61068f0","status":"active"},"success":true,"errors":[],"messages":[{"code":10000,"message":"This API Token is valid and active","type":null}]}

Now we can proceed with our Python script, we install the library:

pip install cloudflare

We write the script:

vi getCloudflareDns.py

#!/usr/local/bin/python3.8
import CloudFlare
import json

credential_tokens = {
  'XXXX': 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
  'XXXX': 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
  'XXXX': 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY',
  'XXXX': 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
}

for account, token in credential_tokens.items():
    print('---------------------------------------------------------')
    print('>> Account: % s -- Token: %s' % (account, token))

    cf = CloudFlare.CloudFlare(token=token, raw=True)
    page_number_domains = 0
    while True:
        page_number_domains += 1
        try:
            raw_results_domains = cf.zones.get(params={'per_page':5,'page':page_number_domains})
        except CloudFlare.exceptions.CloudFlareAPIError as e:
            exit('/zones.get %d %s - api call failed' % (e, e))
        except Exception as e:
            exit('/zones.get - %s - api call failed' % (e))
        
        #print(json.dumps(raw_results_domains, indent=4, sort_keys=True))

        zones = raw_results_domains['result']
        for zone in zones:
            zone_id = zone['id']
            zone_name = zone['name']
            print('-------- ZONE: %s --------' % zone_name)

            page_number_dns = 0
            while True:
                page_number_dns += 1
                try:
                    raw_results_dns = cf.zones.dns_records.get(zone_id, params={'per_page':5,'page':page_number_dns})
                except CloudFlare.exceptions.CloudFlareAPIError as e:
                    exit('/zones/dns_records.get %d %s - api call failed' % (e, e))
                
                #print(json.dumps(raw_results_dns, indent=4, sort_keys=True))

                dns_records = raw_results_dns['result']
                for dns_record in dns_records:
                    dns_id = dns_record['id']
                    dns_name = dns_record['name']
                    dns_type = dns_record['type']
                    dns_value = dns_record['content']
                    print('NAME: %s, TYPE: %s, VALUE: %s' % (dns_name, dns_type, dns_value))

                total_pages_dns = raw_results_dns['result_info']['total_pages']
                #print('page_number_dns: %s total_pages_dns: %s' % (page_number_dns, total_pages_dns))
                if page_number_dns == total_pages_dns:
                    break


        total_pages_domains = raw_results_domains['result_info']['total_pages']
        #print('page_number_domains: %s total_pages_domains: %s' % (page_number_domains, total_pages_domains))
        if page_number_domains == total_pages_domains:
            break

We assign the necessary permissions and execute it:

chmod 700 getCloudflareDns.py

./getCloudflareDns.py
If you liked the article, you can treat me to a RedBull here