]> code.delx.au - monosys/blob - scripts/dyndns
Rearranged, tidied, deleted things, moved things
[monosys] / scripts / dyndns
1 #!/usr/bin/python2
2
3 from datetime import datetime
4 import os
5 import subprocess
6 import sys
7 import re
8
9
10 def increment_serial(line):
11 current_serial = re.search(R"\b\d\d*\b", line).group(0)
12
13 current = int(current_serial)
14 current_num = current % 100
15 current_date = (current - current_num) / 100
16 new_date = int(datetime.now().strftime("%Y%m%d"))
17 if current_date == new_date:
18 next_num = current_num + 1
19 else:
20 next_num = 0
21
22 if next_num >= 100:
23 raise ValueError("Too many serial changes today!")
24 new_serial = str(new_date) + str(next_num).zfill(2)
25 line = line.replace(current_serial, new_serial)
26
27 return line
28
29 def replace_ip(line):
30 source_ip, source_port, dest_ip, dest_port = os.environ["SSH_CONNECTION"].split()
31 line = re.sub(R"\b\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?\b", source_ip, line)
32 return line
33
34
35 def main(live, zonefile, dnslabel):
36 f = open(zonefile)
37 out = []
38 for line in f:
39 if line.find("Serial") >= 0:
40 out.append(increment_serial(line))
41 elif line.find("DYNDNS") >= 0 and line.find("bnet") >= 0:
42 out.append(replace_ip(line))
43 else:
44 out.append(line)
45
46 f.close()
47
48 if live:
49 outf = open(zonefile, "w")
50 outf.writelines(out)
51 outf.close()
52 subprocess.check_call(["sudo", "/etc/init.d/bind9", "reload"])
53 else:
54 sys.stdout.writelines(out)
55
56
57 if __name__ == "__main__":
58 live = False
59 try:
60 i = 1
61 if sys.argv[1] == "live":
62 live = True
63 i = 2
64 zonefile = sys.argv[i]
65 dnslabel = sys.argv[i+1]
66 except:
67 print >>sys.stderr, "Usage: %s [go] zonefile dnslabel" % sys.argv[0]
68 sys.exit(1)
69
70 main(live, zonefile, dnslabel)
71
72