cloudflare-dns-updater/cloudflare_script.py
2022-11-27 18:50:01 +01:00

102 lines
3.6 KiB
Python

import sys
import ipaddress
from configparser import ConfigParser
import json
import CloudFlare
def main():
config = ConfigParser()
config.read('config.ini')
try:
ipversion = sys.argv[1].lstrip('-')
ip_address_new = sys.argv[2]
except IndexError:
ip_address_new = ''
ipversion = 'skipping'
hostname = config['server']['HOSTNAME']
cf = CloudFlare.CloudFlare(token=config['cloudflare']['TOKEN'])
zones = cf.zones.get()
for zone in zones:
zone_id = zone['id']
zone_name = zone['name']
print("zone_id=%s zone_name=%s" % (zone_id, zone_name))
dns_records = cf.zones.dns_records.get(zone_id)
dns_names = {'A' : [], 'AAAA' : []}
for dnsrecord in dns_records:
if ipversion == 'skipping':
print(f"DNS Name: {dnsrecord['name']} | ID: {dnsrecord['id']} | Type : {dnsrecord['type']} | IP: {dnsrecord['content']}")
if dnsrecord['type'] in ['A', 'AAAA']:
dns_names[dnsrecord['type']].append(dnsrecord["name"])
else:
print(f"Cannot resolve record {dnsrecord['name']} because of type {dnsrecord['type']}")
print(f"------ Full DNS record ------\n"
f"{dnsrecord}"
f"\n---------------------------"
)
with open('cloudflare.json', 'r') as file:
values = json.load(file)
print(values)
match ipversion:
case '4':
print("Updating IPv4")
assert isinstance(ipaddress.ip_address(ip_address_new), ipaddress.IPv4Address), f'IP {ip_address_new} is not a valid IPv4 address'
names_replace = values['A']
print(names_replace)
for name in names_replace:
fullname = f"{name}.{hostname}"
print(fullname)
for x in dns_records:
if x['name'] == fullname:
dns_record_id = x['id']
print(dns_record_id)
if fullname in dns_names['A']:
new_dnsrecords = {"name": fullname, "type": "A", "content": ip_address_new}
print(f"Sending request {new_dnsrecords}")
try:
r = cf.zones.dns_records.patch(zone_id, dns_record_id, data=new_dnsrecords)
print(r)
except:
print("Error pushing entry")
case '6':
print("Updating IPv6")
assert isinstance(ipaddress.ip_address(ip_address_new), ipaddress.IPv6Address), f'IP {ip_address_new} is not a valid IPv6 address'
names_replace = values['AAAA']
print(names_replace)
for name in names_replace:
fullname = f"{name}.{hostname}"
print(fullname)
for x in dns_records:
if x['name'] == fullname:
dns_record_id = x['id']
print(dns_record_id)
if fullname in dns_names['AAAA']:
new_dnsrecords = {"name": fullname, "type": "AAAA", "content": ip_address_new}
print(f"Sending request {new_dnsrecords}")
try:
r = cf.zones.dns_records.patch(zone_id, dns_record_id, data=new_dnsrecords)
print(r)
except:
print("Error pushing entry")
case 'skipping':
print("Done")
case other:
print(f"Error with Ip version passed, {ipversion} is invalid")
if __name__ == '__main__':
main()