2019-10-14 17:00:55 +13:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
import socket
|
|
|
|
|
|
|
|
|
|
import click
|
|
|
|
|
import requests
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@click.command()
|
|
|
|
|
@click.option('--hostname', required=False, help='The FQDN you wish to update for DynamicDNS on DirectAdmin server')
|
|
|
|
|
@click.option('--url', required=False, help='The FQDN to access DirectAdmin server e.g https://my.directadmin.com:2222')
|
|
|
|
|
@click.option('--username', required=False, help='The username for your account on DirectAdmin server')
|
|
|
|
|
@click.option('--password', required=False, help='The password for your account on DirectAdmin server')
|
|
|
|
|
def main(hostname, url, username, password):
|
|
|
|
|
click.echo('Updating DNS for ' + hostname)
|
|
|
|
|
(directadmin_zone, directadmin_name) = get_zone_and_name(hostname)
|
|
|
|
|
|
2019-10-15 22:21:43 +13:00
|
|
|
da_client = ""
|
|
|
|
|
try:
|
|
|
|
|
da_client = get_directadmin_client(url, username, password)
|
|
|
|
|
except DirectAdminClientException as e:
|
|
|
|
|
click.echo(e)
|
|
|
|
|
exit(1)
|
2019-10-14 17:00:55 +13:00
|
|
|
current_ip = requests.get('https://icanhazip.com').text.strip()
|
|
|
|
|
hostname_resolves_to = socket.gethostbyname(hostname).strip()
|
|
|
|
|
|
2019-10-15 22:21:43 +13:00
|
|
|
click.echo("Current External IP: {}".format(current_ip))
|
|
|
|
|
click.echo("Hostname resolves to: {}".format(hostname_resolves_to))
|
2019-10-14 17:00:55 +13:00
|
|
|
|
|
|
|
|
if current_ip != hostname_resolves_to:
|
2019-10-15 22:21:43 +13:00
|
|
|
click.echo("Current IP has changed, updating...")
|
2019-10-14 17:00:55 +13:00
|
|
|
try:
|
|
|
|
|
response = da_client.update_dns_record(directadmin_zone,
|
|
|
|
|
"A",
|
|
|
|
|
directadmin_name,
|
|
|
|
|
hostname_resolves_to,
|
|
|
|
|
current_ip, 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 __name__ == '__main__':
|
|
|
|
|
main()
|