From 888a6071b9950feea1229e5599efe436497dd2b4 Mon Sep 17 00:00:00 2001 From: mortzu Date: Fri, 3 Apr 2015 15:38:41 +0200 Subject: [PATCH] (r)zonegen.py: Use ipaddress module and Python 3 --- rzonegen.py | 29 +++++++++++------------------ zonegen.py | 17 +++++++++++------ 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/rzonegen.py b/rzonegen.py index 23a3980..78b34c8 100755 --- a/rzonegen.py +++ b/rzonegen.py @@ -1,9 +1,9 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys import json -import codecs import re +import ipaddress from datetime import datetime def str_to_domainlabel(s): @@ -17,19 +17,7 @@ def str_to_domainlabel(s): return label def ipv6_addr_to_rdns(addr): - rdns = "" - counter = 4 - - for char in reversed(addr): - if char == ':': - rdns += counter * '0.' - counter = 4 - else: - rdns += char + '.' - counter -= 1 - - rdns += 'ip6.arpa.' - return rdns + return ".".join(reversed(addr.exploded.replace(':', ''))) + ".ip6.arpa." data = json.load(sys.stdin) domain = sys.argv[1] @@ -54,12 +42,17 @@ print("""$TTL 1h for node in data.values(): try: for address in node['network']['addresses']: - if address.startswith("fe80:"): + try: + address = ipaddress.IPv6Address(address) + except ValueError: + continue + + if address.is_link_local or address.is_private: continue rdns = ipv6_addr_to_rdns(address) if rdns.endswith(domain): - print "%s PTR %s.nodes.ffhb." % (ipv6_addr_to_rdns(address)[0:-len(domain)], str_to_domainlabel(node['hostname'])) - except: + print("%s PTR %s.nodes.ffhb.de." % (rdns[0:-len(domain)], str_to_domainlabel(node['hostname']))) + except (KeyError, RuntimeError): pass diff --git a/zonegen.py b/zonegen.py index b45b67c..23fb2a0 100755 --- a/zonegen.py +++ b/zonegen.py @@ -1,9 +1,9 @@ -#! /usr/bin/env python +#! /usr/bin/env python3 import sys import json -import codecs import re +import ipaddress from datetime import datetime def str_to_domainlabel(s): @@ -19,7 +19,7 @@ def str_to_domainlabel(s): data = json.load(sys.stdin) -print """$TTL 1h +print("""$TTL 1h @ IN SOA vpn01.bremen.freifunk.net. noc.bremen.freifunk.net. ( %s ; serial 1h ; refresh @@ -30,14 +30,19 @@ print """$TTL 1h NS vpn01.bremen.freifunk.net. -""" % datetime.now().strftime("%Y%m%d%H%M") +""" % datetime.now().strftime("%Y%m%d%H%M")) for node in data.values(): try: for address in node['network']['addresses']: - if address.startswith("fe80:"): + try: + address = ipaddress.IPv6Address(address) + except ValueError: continue - print "%-15s AAAA %s" % (str_to_domainlabel(node['hostname']), address) + if address.is_link_local or address.is_private: + continue + + print("%-15s AAAA %s" % (str_to_domainlabel(node['hostname']), address)) except: pass