Files
dnsupdate/dnsupdate.py

106 lines
3.1 KiB
Python

# dnsupdate.py
# Updates a dynamic dns-record using a TSIG key.
class dnsvalues:
def __init__(self):
self.domain = "lubcke.se"
self.keyname = "lubcke.se."
self.keysecret = "ZGhNJ05b8ThmHOXhJvkvMw=="
self.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():
from optparse import OptionParser
import sys
# 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 [auto detected]")
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()
if options.ipaddress:
msg.ipaddress = options.ipaddress
else:
msg.ipaddress = get_ipaddress()
if options.domain:
msg.domain = options.domain
if options.keyname:
msg.keyname = options.keyname
if options.password:
msg.keysecret = options.password
if options.ttl:
msg.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:
msg.hostname = options.name
update()
def update():
import dns.query
import dns.tsigkeyring
import dns.update
import re
import string
# The update function connects to the dns server
# Sanity check incoming data
#global hostname, ipaddress, ttl
msg.hostname = string.replace(msg.hostname, "."+msg.domain, '')
if not re.search('^[12]?[0-9]?[0-9](\.[12]?[0-9]?[0-9]){3}$', msg.ipaddress):
print "Invalid ip address '%s'" % msg.ipaddress
return
# The name of the key and the secret
keyring = dns.tsigkeyring.from_text({
msg.keyname: msg.keysecret
})
# dns.update.Update(name of domain, keyring, keyname)
update = dns.update.Update(msg.domain, keyring=keyring, keyname=msg.keyname)
# update.replace(hostname, ttl, record-type, new ip)
update.replace(msg.hostname, msg.ttl, 'a', msg.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" % (msg.hostname, msg.domain, msg.ipaddress)
else:
print "An error has occurred, the server returned:\n%s" % response
if __name__=="__main__":
msg = dnsvalues()
main()