4 from subprocess import Popen, PIPE
8 def ipfamily_by_ip(ip):
9 if isinstance(ip, ipaddr.IPv4Address):
11 elif isinstance(ip, ipaddr.IPv6Address):
16 def nsupdate_add(hostname, domain, ttl, ip):
17 """ip_family: A or AAAA"""
18 command = "update add {hostname}.{domain} {ttl} IN {ip_family} {ip}\n\n".format(hostname=hostname, domain=domain, ttl=ttl, ip_family=ipfamily_by_ip(ip), ip=ip)
19 p = Popen(['nsupdate', '-l'], stdin=PIPE)
20 p.communicate(command)
23 def nsupdate_delete(hostname, domain, ip_family):
24 """ip_family: A or AAAA"""
25 command = "update delete {hostname}.{domain} {ip_family}\n\n".format(hostname=hostname, domain=domain, ip_family=ip_family)
26 p = Popen(['nsupdate', '-l'], stdin=PIPE)
27 p.communicate(command)
32 nsupdate_delete(args.hostname, args.domain, 'A')
33 nsupdate_delete(args.hostname, args.domain, 'AAAA')
35 nsupdate_delete(args.hostname, args.domain, ipfamily_by_ip(args.ip))
36 nsupdate_add(args.hostname, args.domain, args.ttl, args.ip)
39 if __name__ == '__main__':
40 parser = argparse.ArgumentParser(description='Add or delete a hostname from dyndns (simplifies call to nsupdate).')
41 parser.add_argument('-d', '--delete', action='store_true', help='delete instead of add')
42 parser.add_argument('-i', '--ip', help='IP address (either IPv4 or IPv6)')
43 # parser.add_argument('-t', '--ttl', type=int, default=600, help='TTL (default: 600)')
44 parser.add_argument('hostname', help='hostname to add or delete, e.g. myserver')
45 args = parser.parse_args()
47 args.domain = 'dyn.colgarra.priv.at' # <---- TODO
48 args.ttl = 600 # <---- TODO
51 if not args.delete and not args.ip:
52 parser.error('The IP address is mandatory')
55 args.ip = ipaddr.IPAddress(args.ip) # throws an exception if the IP address is not valid
57 parser.error('The IP address is not valid')
60 if re.match(r'[-0-9a-z]+(\.[-0-9a-z]+)*$', args.hostname) is None:
61 parser.error('The hostname has an invalid format.')