aboutsummaryrefslogtreecommitdiffstats
path: root/zoneupdate.py
blob: 215709c06f6c2b36467699a9516c708169acaa67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python

import dns.zone
import dns.resolver
from urllib2 import urlopen

from config import CONFIG

origin = CONFIG['origin']
zonefile = CONFIG['zonefile']

zone = dns.zone.from_file(zonefile, origin)

# Fetch our external IP address
url = urlopen(CONFIG['lookup_url'])
ip4 = url.read().strip()
url.close()

A = zone.find_rdataset(CONFIG['host'], 'A')
TXT = zone.find_rdataset(CONFIG['host'], 'TXT')

for rdata in A:
    # Don't do anything unless the the IPv4 address in the zone file is wrong
    if not rdata.address == ip4:
        rdata.address = ip4

        # Remove any existing TXT record(s) and replace with a new one
        # Method for adding gleaned from https://github.com/vimalloc/easyzone/blob/master/easyzone/easyzone.py
        for txtdata in TXT:
            TXT.remove(txtdata)
        txt = 'v=spf1 ip4:' + ip4 + ' -all'
        rd = dns.rdtypes.ANY.TXT.TXT(dns.rdataclass.IN, dns.rdatatype.TXT, txt)
        TXT.add(rd)

        # Fetch the serial number that the world sees and leapfrog it.
        # The serial number we set here has to be higher than the DNSSEC signed
        # version so that ods-signer will recognize that it is a new version.
        # ods-signer will increment this serial once more when signing the zone.
        query = dns.resolver.query(origin, 'SOA')
        for (name, ttl, zrdata) in zone.iterate_rdatas('SOA'):
            for qrdata in query:
                zrdata.serial = qrdata.serial + 2

        zone.to_file(zonefile)