bin/pvl.hosts-reverse
author Tero Marttila <terom@paivola.fi>
Mon, 09 Mar 2015 19:48:19 +0200
changeset 735 008cfe47b194
parent 670 b95ad8c8bb4e
permissions -rwxr-xr-x
pvl.hosts.interface: sub-interfaces for a host, which are not associated with any separate domain/network
#!/usr/bin/env python

import logging; log = logging.getLogger('pvl.hosts-reverse')
import optparse 
import os.path
import pvl.args
import pvl.hosts
import pvl.hosts.interface
import pvl.hosts.zone

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.config.optparser(parser))

    parser.add_option('--zone-prefix',          metavar='PREFIX',
            help="Generated records for given prefix's reverse zone origin")

    parser.add_option('--unknown-host',         metavar='NAME',
            help="Generate records for unused IPs")

    # input
    options, args = pvl.args.parse(parser, argv)
 
    if options.zone_prefix:
        try:
            prefix = pvl.dns.parse_prefix(options.zone_prefix)
        except ValueError as error:
            log.error("invalid reverse --zone-prefix=%s: %s", options.zone_prefix, error)
            return 1
        else:
            log.info("using given reverse --zone-prefix: %s", prefix)
   
    elif len(args) == 1:
        path, = args
        zone_prefix = os.path.basename(path.rstrip('/'))

        try:
            prefix = pvl.dns.parse_prefix(zone_prefix)
        except ValueError as error:
            log.error("invalid hosts path %s for reverse --zone-prefix: %s", zone_prefix, error)
            return 1
        else:
            log.info("using given hosts path %s for reverse --zone-prefix: %s", zone_prefix, prefix)

    elif args:
        log.fatal("--zone-prefix is required if passing multiple hosts files")
        return 1

    else:
        log.fatal("no hosts given as input")
        return 1
 
    if options.unknown_host and not options.hosts_domain:
        log.fatal("--unknown-host requires --hosts-domain=")
        return 1

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

    # process
    try:
        for rr in pvl.hosts.zone.apply_hosts_reverse(hosts, prefix,
                unknown_host    = options.unknown_host,
                unknown_domain  = options.hosts_domain,
        ):
            print unicode(rr)

    except pvl.hosts.HostError as error:
        log.error("%s", error)
        return 3

    return 0

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