zoneupdate/zoneupdate.py

76 lines
2.8 KiB
Python

#! /usr/bin/env python3
import requests
import json
import yaml
import re
from yaml.loader import SafeLoader
with open ('/etc/zoneupdate.conf', 'r') as file:
config = yaml.safe_load(file)
def get_current_public_ip(ip_services, debug=False):
'''
resolve public ip using simple service, from github.com/fyah/gandi-api-v5/gandyn-livedns.py
'''
for service in ip_services:
try:
r = requests.get(service)
res = r.text
if re.match('\d+\.\d+\.\d+\.\d+', res):
return res
except Exception as e:
#there was a problem resolving our public with the service...
if debug:
print ('Failed to resolve public ip using %s' % service)
print (e)
#try with next
continue
def get_sub_records(domain, subdomain, api_url, api_key, debug=False):
url = api_url + '/domains/' + domain + '/records/' + subdomain
headers = {'Authorization': "Apikey " + api_key}
resp = requests.get(url, headers=headers)
json_object = json.loads(resp._content)
return json_object[0]
def update_sub_records(domain, subdomain, api_url, api_key, ip, ttl, debug=False):
url = api_url + '/domains/' + domain + '/records/' + subdomain
payload = {"rrset_type": "A", "rrset_ttl": ttl, "rrset_values": [ip]}
items = {"items": [payload]}
headers = {'Content-Type': 'application/json', 'Authorization': "Apikey " + api_key}
resp = requests.put(url, data=json.dumps(items), headers=headers)
json_object = json.loads(resp._content)
return json_object
for zone in config['zones']:
domain = zone['domain']
for subdomain in zone['subdomains']:
url = subdomain + '.' + domain
api_url=config['api_url']
api_key=zone['api_key']
debug=config['debug']
ttl=config['ttl']
ip_services=config['ip_services']
print ("Checking IP of %s" % url)
try:
sub_records = get_sub_records(domain,subdomain,api_url=api_url,api_key=api_key,debug=debug)
old_ip=(sub_records['rrset_values'])
old_ip=old_ip[0]
new_ip=get_current_public_ip(ip_services=ip_services, debug=debug)
except Exception as e:
print ('Failed to find sub-record for domain %s, attempting to create' % url)
new_ip=get_current_public_ip(ip_services=ip_services, debug=debug)
resp = update_sub_records(domain,subdomain,api_url=api_url,api_key=api_key,ip=new_ip,ttl=ttl,debug=debug)
print (resp)
continue
if new_ip != old_ip:
print ('IP check failed, updating')
resp = update_sub_records(domain,subdomain,api_url=api_url,api_key=api_key,ip=new_ip,ttl=ttl,debug=debug)
print (resp)
else:
print ('IP check complete')