Compare commits

..
9 Commits
Author SHA1 Message Date
pavak 9ffa3cd076 renamed API Key to API Token 2022-06-01 20:39:58 +05:30
pavak e95018240c added instructions 2022-06-01 20:22:08 +05:30
pavak 49e7cd13b6 formatting and cleanup 2022-06-01 18:07:05 +05:30
pavak bb80e40ce9 Completed 2022-06-01 01:56:44 +05:30
pavak 254615eda6 added DNS export files to gitignore 2022-05-31 23:06:03 +05:30
pavak 48cfb3ee87 getAllDNS, deleteARecord and some main file logics 2022-05-28 02:06:26 +05:30
pavak 790a38a970 verify access and list zones 2022-05-27 01:47:43 +05:30
pavak 81cd95924e Get credentials 2022-05-27 00:12:23 +05:30
pavak fbecb310a5 fixed typo 2022-05-27 00:11:06 +05:30
5 changed files with 183 additions and 2 deletions

No files matched your search

+2
View File
@@ -169,3 +169,5 @@ cython_debug/
# Project setup
config.json
response-example*
dns-export*
+47
View File
@@ -1,3 +1,50 @@
# cloudflare-delete-all-dns-records
Delete all the DNS records in a domain in Cloudflare.
This program will delete all the DNS records in a given domain. Before deletion, it'll also take a backup of the existing DNS records and save it as a .txt file in [BIND](https://www.isc.org/bind/) format.
## Prerequisites
- [Python 3](https://www.python.org/)
- Pip
>sudo apt install python3-pip
- [Python requests library](https://pypi.org/project/requests/)
>pip install requests
- CloudFlare API key
You need a CloudFlare API key with access to *edit zone DNS* access for the domain:
1. Go to your Cloudflare profile and then [API Tokens](https://dash.cloudflare.com/profile/api-tokens)
2. Click on *Create Token*
3. You can use the template *Edit Zone DNS*
4. Enter the of the domain(s) you want to delete DNS from in *Zone Resources*
5. Click *Continue to summary* and the *Create Token*
6. You should get an API Token now.
## Running the program
1. Download and extract the zip file or Clone this repository:
>git clone https://git.pavakpaul.com/pavak/cloudflare-delete-all-dns-records.git
2. cd to the directory:
>cd
cloudflare-delete-all-dns-records
3. Run app.py using python3 and follow the instructions
>python3 app.py
### Using a config file to pass the API credentials
If you want to delete all the DNS records from multiple domains, it is a good idea to use a single token for mutiple domains. In that case, you can use save your credentials in config.json. Simply rename config_sample.json to config.json: `mv config_sample.json config.json` and save your configuration there. To load the config file, simply pass the argument _loadconfig_:
>python3 app.py loadconfig
You still can't delete DNS from multiple domains to reduce accidental removals of DNS. To be safe, it's always a good idea to just create a token for a single domain.
+56
View File
@@ -0,0 +1,56 @@
import requests
def getHeaders(credentials):
headers = {'Authorization': f'Bearer {credentials["api_key"]}', 'X-Auth-Email': f'{credentials["email"]}',
'Content-Type': 'application/json'}
return headers
def errorChecker(r):
if r.status_code == 200:
return False
elif r.status_code == 429:
print(f'\n\n\n{"="*80}It looks like you have reached your rate limit to access CloudFlare APIs\nPlease try after 5 minutes.{"="*80}')
else:
print(f'Error {r.status_code}.\nDetails:\n{r.json()}')
assert False
def verifyCredentials(credentials):
headers = getHeaders(credentials)
r = requests.get('https://api.cloudflare.com/client/v4/user/tokens/verify', headers=headers)
errorChecker(r)
return r
def listAllZones(credentials):
zones = requests.get(
'https://api.cloudflare.com/client/v4/zones',
headers= getHeaders(credentials)
)
errorChecker(zones)
return zones
def getAllDNS(credentials, id):
dns_records = requests.get(
f'https://api.cloudflare.com/client/v4/zones/{id}/dns_records',
headers=getHeaders(credentials)
)
errorChecker(dns_records)
return dns_records
def exportBindDNS(credentials, id):
export_response = requests.get(
f'https://api.cloudflare.com/client/v4/zones/{id}/dns_records/export',
headers=getHeaders(credentials)
)
errorChecker(export_response)
return export_response
def deleteARecord(credentials, zone_id, dns_id):
delete_response = requests.delete(
f'https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{dns_id}',
headers=getHeaders(credentials)
)
errorChecker(delete_response)
return delete_response
+77
View File
@@ -0,0 +1,77 @@
import json
import uuid
import datetime
from fileinput import filename
from sys import argv
from pathlib import Path
from apicalls import *
# Get API tocken and Email address
def getCredentials():
api_key = input("Enter the Cloudflare API token: ")
email_address = input("Enter the Cloudflare Email address: ")
return {"api_key": api_key, "email": email_address}
# Get credentials
if len(argv) > 1 and 'loadconfig' in argv:
if Path("config.json").exists():
configfile = open("config.json")
config = json.load(configfile)
credentials = {
'api_key': config['API_Token'], 'email': config['Email']}
else:
print('config.json was not found. Please enter the credentials manually')
credentials = getCredentials()
else:
credentials = getCredentials()
zones = listAllZones(credentials).json()["result"]
print('Here are the domains in your account')
zone_index = 0
zone_list = {}
for zone in zones:
print(f'{zone_index + 1}: {zone["name"]}')
zone_list[zone['name']] = {'id': zone['id'], 'name': zone['name'], 'owner': zone['owner']['email'], 'account_of': zone['account']['name']}
domainToDelete = input('Please enter the domain name to delete the DNS records from:\n')
if domainToDelete in zone_list:
zone_id = zone_list[domainToDelete]['id']
zone_owner = zone_list[domainToDelete]['owner']
confirmation = input(f'Are you sure to delete all the DNS records from the domain {domainToDelete}, owned by {zone_owner}?\nEnter YES to continue: ')
if confirmation == 'YES':
# Get Bind DNS
bind_DNS = exportBindDNS(credentials, zone_id).text
# Write to a file
file_name = f'dns-export-{str(uuid.uuid4())[0:8]}-{domainToDelete}-{datetime.datetime.now().strftime("%d-%b-%Y-%H-%M-%S")}.txt'
print(f'Backing up DNS records to {file_name}')
bind_export_file = open(file_name, 'w')
bind_export_file.write(bind_DNS)
bind_export_file.close()
print('Successfully backed up DNS records in BIND format.')
# get DNS Records
dns_records = getAllDNS(credentials, zone_id).json()["result"]
# Delete DNS Records
print('Starting Deletion of DNS records')
for record in dns_records:
dns_id = record['id']
dns_type = record['type']
dns_name = record['name']
dns_content = record['content']
print(f'Deleting:\n{dns_type}\t{dns_name}\t{dns_content}...')
delete_response = deleteARecord(credentials, zone_id, dns_id)
if delete_response.json()['result']['id'] == dns_id:
print(f'Successfully Deleted {dns_id}')
else:
print('Something is wrong, abroading...')
assert False
else:
print('Aborted, bye...')
else:
print('We don\'t have access to the domain name you have entered. Please make sure the API token you have provided has access to the domain name you have entereed.')
+1 -2
View File
@@ -1,5 +1,4 @@
{
"saveCredentials": true,
"API_KEY": "your api key goes here",
"API_Token": "your api key goes here",
"Email": "your cloudflare email address"
}