bin/pvl.hosts-dns
author Tero Marttila <terom@paivola.fi>
Mon, 16 Dec 2013 19:00:58 +0200
changeset 270 bafcda3a3c0d
parent 269 713d0495288e
child 272 5755f9c54135
permissions -rwxr-xr-x
pvl.hosts-dns: split to pvl.dns.host, using Host class
#!/usr/bin/env python

import pvl.args
import pvl.hosts
import pvl.dns.zone

import ipaddr
import logging; log = logging.getLogger('pvl.hosts-dns')
import optparse

def process_hosts_forward (options, hosts, domain) :
    """
        Generate DNS ZoneRecords for the given domain's zone for hosts.
    """

    for host in hosts :
        if options.forward_zone and host.domain != domain :
            continue
        
        if host.ip :
            yield pvl.dns.zone.ZoneRecord.A(host, host.ip)
        
        for alias in host.alias :
            yield pvl.dns.zone.ZoneRecord.CNAME(alias, host)

def process_hosts_reverse (options, hosts, prefix) :
    """
        Generate DNS ZoneRecords within the given prefix's reverse-dns zone for hosts.
    """

    for host in hosts :
        if not host.ip :
            continue

        if host.ip not in prefix :
            continue
        
        # reverse against the reverse-dns zone origin
        yield pvl.dns.zone.ZoneRecord.PTR(
                pvl.dns.zone.reverse_label(prefix, host.ip),
                pvl.dns.zone.fqdn(host, host.domain)
        )

def apply_zone (options, zone) :
    """
        Output given ZoneRecord's
    """

    for record in zone :
        print unicode(record)

def main (argv) :
    """
        Generate bind zonefiles from host definitions.
    """

    parser = optparse.OptionParser(main.__doc__)
    parser.add_option_group(pvl.args.parser(parser))
    parser.add_option_group(pvl.hosts.optparser(parser))

    parser.add_option('--forward-zone',         metavar='DOMAIN',
            help="Generate forward zone for domain")

    parser.add_option('--reverse-zone',         metavar='PREFIX',
            help="Generate reverse zone for prefx")

    options, args = parser.parse_args(argv[1:])
    pvl.args.apply(options)

    # input
    hosts = pvl.hosts.apply(options, args)

    # process
    if options.forward_zone :
        apply_zone(options, 
                process_hosts_forward(options, hosts, options.forward_zone),
        )
    
    if options.reverse_zone :
        apply_zone(options, 
                process_hosts_reverse(options, hosts, ipaddr.IPNetwork(options.reverse_zone)),
        )

if __name__ == '__main__':
    pvl.args.main(main)