Skip to content

Instantly share code, notes, and snippets.

@conqp
Last active December 26, 2020 14:12
Show Gist options
  • Save conqp/ba028e7c7cd30363a7484910c14e4781 to your computer and use it in GitHub Desktop.
Save conqp/ba028e7c7cd30363a7484910c14e4781 to your computer and use it in GitHub Desktop.
Script to update DynDNS hosts registered at ddnss.de
#! /usr/bin/env python3
# ddnssupdate.py - Script to update DynDNS hosts registered at ddnss.de.
#
# Copyright (C) 2020 Richard Neumann <mail at richard dash neumann period de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Updates ddnss.de domains."""
from argparse import ArgumentParser, Namespace
from configparser import ConfigParser
from logging import DEBUG, INFO, basicConfig, getLogger
from pathlib import Path
from re import search
from sys import exit # pylint: disable=W0622
from urllib.error import URLError
from urllib.parse import urlencode, urlunparse
from urllib.request import urlopen
LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s'
LOGGER = getLogger(Path(__file__).name)
REGEX = '(Updated \\d+ hostname\\.)'
URL = ('https', 'ddnss.de', 'upd.php')
class UpdateError(Exception):
"""Indicates an error during the update."""
def update(host: str, key: str) -> str:
"""Updates the respective host using the provided key."""
params = {'host': host, 'key': key}
url = urlunparse((*URL, None, urlencode(params), None))
LOGGER.debug('Update URL: %s', url)
with urlopen(url) as response:
text = response.read().decode()
match = search(REGEX, text)
if match:
return match.group(1)
raise UpdateError(text)
def get_args() -> Namespace:
"""Parses the CLI arguments."""
parser = ArgumentParser(description='Update ddnss.de domains.')
parser.add_argument('host', help='the host to update')
parser.add_argument('-k', '--key', metavar='key', help='the update key')
parser.add_argument('-d', '--debug', action='store_true',
help='verbose logging')
return parser.parse_args()
def main():
"""Runs the CLI program."""
args = get_args()
basicConfig(level=DEBUG if args.debug else INFO, format=LOG_FORMAT)
config = ConfigParser()
config.read('/etc/ddnss.conf')
if (key := args.key is None):
try:
key = config.get(args.host, 'key')
except KeyError:
LOGGER.error('No key configured for host "%s".', args.host)
exit(2)
try:
message = update(args.host, key)
except URLError as error:
LOGGER.error('Failed to connect to service.')
LOGGER.debug(error)
exit(3)
except UpdateError as error:
LOGGER.error('Failed to update host.')
LOGGER.debug(error)
exit(4)
LOGGER.info(message)
exit(0)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment