#!/usr/bin/env python import click import click_config_file import requests import dns.resolver import tldextract from lib.directadmin import DirectAdminClient, DirectAdminClientException def get_zone_and_name(record_domain): """Find a suitable zone for a domain :param str record_name: the domain name :returns: (the zone, the name in the zone) :rtype: tuple """ (subdomain, domain, suffix) = tldextract.extract(record_domain) directadmin_zone = ".".join((domain, suffix)) directadmin_name = subdomain return directadmin_zone, directadmin_name def get_directadmin_client(url, username, password): return DirectAdminClient( url, username, password) def getipv6(hostname): answers = dns.resolver.query(hostname, 'AAAA') for ip in answers: return str(ip).strip() def getipv4(hostname): answers = dns.resolver.query(hostname, 'A') for ip in answers: return str(ip).strip() @click.command() @click_config_file.configuration_option() @click.option('--hostname', help='The FQDN you wish to update for DynamicDNS on DirectAdmin server') @click.option('--url', help='The FQDN to access DirectAdmin server e.g https://my.directadmin.com:2222') @click.option('--username', help='The username for your account on DirectAdmin server') @click.option('--password', help='The password for your account on DirectAdmin server') def ddns_updater(hostname, url, username, password): click.echo('Updating DNS for ' + hostname) (directadmin_zone, directadmin_name) = get_zone_and_name(hostname) da_client = "" try: da_client = get_directadmin_client(url, username, password) except DirectAdminClientException as e: click.echo(e) exit(1) current_ip4 = requests.get('http://icanhazip.com').text.strip() # current_ip6 = requests.get('http://ip1.dynupdate6.no-ip.com').text.strip() hostname_resolves_to_ip4 = getipv4(hostname) # hostname_resolves_to_ip6 = getipv6(hostname) click.echo("Current External IP: {}".format(current_ip4)) click.echo("Hostname resolves to: {}".format(hostname_resolves_to_ip4)) # click.echo("Current External IP6: {}".format(current_ip6)) # click.echo("Hostname resolves to: {}".format(hostname_resolves_to_ip6)) if current_ip4 != hostname_resolves_to_ip4: click.echo("Current V4 IP has changed, updating...") try: response = da_client.update_dns_record(directadmin_zone, "A", directadmin_name, hostname_resolves_to_ip4, current_ip4, 30) if int(response['error']) == 0: click.echo("Successfully updated A record for " + hostname) except DirectAdminClientException as e: click.echo("Error updating A record: %s" % e) # # if current_ip6 != hostname_resolves_to_ip6: # click.echo("Current V6 IP has changed, updating...") # try: # response = da_client.update_dns_record(directadmin_zone, # "AAAA", # directadmin_name, # hostname_resolves_to_ip6, # current_ip6, 30) # if int(response['error']) == 0: # click.echo("Successfully updated AAAA record for " + hostname) # except DirectAdminClientException as e: # click.echo("Error updating AAAA record: %s" % e) if __name__ == '__main__': ddns_updater()