Last active
March 10, 2021 08:15
-
-
Save frjo/3e8c2c311afadccd85f93900730bf740 to your computer and use it in GitHub Desktop.
Script to update DNS entries for a list of domains via GlySYS API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Script to update DNS entries for a list of domains via GlySYS API. | |
""" | |
import argparse | |
import ipaddress | |
import logging | |
import os | |
import requests | |
from logging.handlers import RotatingFileHandler | |
# Set variables. | |
apikey = 'CHANGE_THIS_to_your_api_key' | |
apiurl = 'https://api.glesys.com/domain/updaterecord/' | |
apiuser = 'CHANGE_THIS_to_your_api_user' | |
current_ip_file = '/var/spool/dynamicdns/current_ip.txt' | |
dns_records = { | |
'12345': 'example.org', | |
'23456': 'vpn.example.org', | |
'34567': 'server.example.org', | |
} | |
def logger(): | |
logfile = '/var/log/dynamicdns.log' | |
log_format = ('%(asctime)s %(levelname)-8s %(message)s') | |
logging.basicConfig( | |
level=logging.INFO, | |
format=log_format, | |
handlers=[ | |
RotatingFileHandler(logfile, maxBytes=50000) | |
], | |
) | |
return logging.getLogger(__name__) | |
logger = logger() | |
def updatedns(recordid, new_ip_address): | |
r = requests.post(apiurl, auth=(apiuser, apikey), headers={'accept': 'application/json'}, data={'recordid': recordid, 'data': new_ip_address}) | |
output = r.json() | |
response_code = output['response']['status']['code'] | |
response_text = output['response']['status']['text'] | |
response_ip = output['response']['record']['data'] | |
if response_code == 200: | |
logger.info(f'{dns_records[recordid]} has been updated to IP {response_ip}') | |
else: | |
logger.error(f'{dns_records[recordid]} could not be updated Error code: {response_code} {response_text}') | |
def get_current_ip(): | |
current_ip = None | |
try: | |
with open(current_ip_file, 'r') as f: | |
current_ip = f.read() | |
except FileNotFoundError: | |
pass | |
return current_ip | |
def set_current_ip(new_ip_address): | |
os.makedirs(os.path.dirname(current_ip_file), exist_ok=True) | |
with open(current_ip_file, 'w') as f: | |
f.write(new_ip_address) | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('new_ip_address', type=str, help='The new IP address.') | |
args = parser.parse_args() | |
new_ip_address = args.new_ip_address | |
try: | |
ipaddress.ip_address(new_ip_address) | |
except ValueError: | |
logger.warning(f'Not a valid new IP: {new_ip_address}') | |
else: | |
if new_ip_address != get_current_ip(): | |
set_current_ip(new_ip_address) | |
[updatedns(recordid, new_ip_address) for recordid in dns_records] | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment