#!/bin/python3 import requests import json import toml import re config=toml.load('zoneupdate.toml') 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 domain in config['domains']: for subdomain in config[domain]['subdomains']: url = subdomain + '.' + domain api_url=config['api_url'] api_key=config[domain]['api_key'] debug=config['debug'] ttl=config['ttl'] print ("Checking IP of %s" % url) try: sub_records = get_sub_records(domain,subdomain,api_url=config['api_url'],api_key=config[domain]['api_key'],debug=config['debug']) old_ip=(sub_records['rrset_values']) old_ip=old_ip[0] new_ip=get_current_public_ip(ip_services=config['ip_services'], debug=config['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=config['ip_services'], debug=config['debug']) resp = update_sub_records(domain,subdomain,api_url=config['api_url'],api_key=config[domain]['api_key'],ip=new_ip,ttl=config['ttl'],debug=config['debug']) print (resp) continue if new_ip != old_ip: print ('IP check failed, updating') resp = update_sub_records(domain,subdomain,api_url=config['api_url'],api_key=config[domain]['api_key'],ip=new_ip,ttl=config['ttl'],debug=config['debug']) print (resp) else: print ('IP check complete')