Files
da-ddnsclient/ddns_updater.py

63 lines
2.2 KiB
Python
Raw Normal View History

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)
da_client = get_directadmin_client(url, username, password)
current_ip = requests.get('https://icanhazip.com').text.strip()
hostname_resolves_to = socket.gethostbyname(hostname).strip()
click.echo(current_ip)
click.echo(hostname_resolves_to)
if current_ip != hostname_resolves_to:
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()