Files
dnsupdate/dnsupdate.py

108 lines
3.0 KiB
Python

import dns.query
import dns.tsigkeyring
import dns.update
from optparse import OptionParser
import re
import string
import sys
# dnsupdate.py
# Updates a dynamic dns-record using a TSIG key.
domain = "lubcke.se"
keyname = "lubcke.se."
keysecret = "ZGhNJ05b8ThmHOXhJvkvMw=="
ttl = 60
def get_ipaddress():
# Connects to the dns server to determine which ip address
# this host connects from
import urllib
remote = opener = urllib.FancyURLopener({})
f = opener.open("http://www.wahlberg.se/~fredrik/ip.php")
ip = f.read().strip()
return ip
def main():
# Define option parameters
usage = "usage: %prog [-n] hostname [-i] ip adress [OPTIONS]"
parser = OptionParser(usage)
parser.add_option("-d", "--domain",
type="string",
help="Name of the domain to update")
parser.add_option("-i", "--ipaddress",
type="string",
help="IP-address of the host")
parser.add_option("-k", "--keyname",
type="string",
help="Name of the TSIG key")
parser.add_option("-n", "--name",
type="string",
help="Name of the host to update")
parser.add_option("-p", "--password",
type="string",
help="The TSIG key")
parser.add_option("-t", "--ttl",
type="int",
help="TTL in seconds")
(options, args) = parser.parse_args()
global domain, ipaddress, keyname, keysecret, ttl
if options.domain:
domain = options.domain
if options.ipaddress:
ipaddress = options.ipaddress
else:
ipaddress = get_ipaddress()
if options.keyname:
keyname = options.keyname
if options.password:
keysecret = options.password
if options.ttl:
ttl = options.ttl
if not options.name:
print "A hostname is required for operation.\nEnter '%s -h' for usage information" % sys.argv[0]
return
else:
global hostname
hostname = options.name
update()
def update():
# The update function connects to the dns server
# Sanity check incoming data
global hostname, ipaddress, ttl
hostname = string.replace(hostname, "."+domain, '')
if not re.search('^[12]?[0-9]?[0-9](\.[12]?[0-9]?[0-9]){3}$', ipaddress):
print "Invalid ip address '%s'" % ipaddress
return
# The name of the key and the secret
keyring = dns.tsigkeyring.from_text({
keyname: keysecret
})
# dns.update.Update(name of domain, keyring, keyname)
update = dns.update.Update(domain, keyring=keyring, keyname=keyname)
# update.replace(hostname, ttl, record-type, new ip)
update.replace(hostname, ttl, 'a', ipaddress)
# doit, servername
response = dns.query.tcp(update, 'nic.wahlberg.se')
# Verify response
if response.rcode() == 0:
print "Host '%s.%s' has been added with ip address %s" % (hostname, domain, ipaddress)
else:
print "An error has occurred, the server returned:\n%s" % response
if __name__=="__main__":
main()