Created
November 27, 2023 12:41
-
-
Save dorancemc/5983824005b65669f0137c44b1ed1f64 to your computer and use it in GitHub Desktop.
dnszone2yml.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# Script to convert a DNS zone file to a YAML file | |
# | |
# Usage: | |
# python3 dnszone2yml.py -f /path/to/zonefile -e /path/to/export.yml [--ttl] [-t TYPE [TYPE ...] | |
# --ttl: Print the TTL for each record | |
# -t TYPE [TYPE ...]: Only print records of the specified type(s) (e.g. A, AAAA, CNAME, etc.) | |
# | |
# example: | |
# python3 dnszone2yml.py -f /tmp/db.example.com -e /tmp/example.com.yml --ttl -t A CNAME | |
# | |
import argparse | |
import yaml | |
def sort_dns_data(data): | |
return sorted(data, key=lambda k: k['name']) | |
def parse_dns_file(file_path, pttl=False, options=['all']): | |
dns_data = [] | |
with open(file_path, 'r') as file: | |
for line in file: | |
parts = line.strip().split() | |
if len(parts) >= 4: | |
name = parts[0] | |
ttl = int(parts[1]) | |
record_type = parts[3] | |
content = parts[4] | |
if 'all' in options or record_type in options: | |
if pttl: | |
dns_entry = { | |
'name': name, | |
'records': [ | |
{ | |
'content': content, | |
} | |
], | |
'type': record_type, | |
'ttl': ttl, | |
} | |
else: | |
dns_entry = { | |
'name': name, | |
'records': [ | |
{ | |
'content': content, | |
} | |
], | |
'type': record_type, | |
} | |
dns_data.append(dns_entry) | |
return sort_dns_data(dns_data) | |
def create_yaml_file(data, output_file): | |
with open(output_file, 'w') as file: | |
yaml.dump(data, file, default_flow_style=False, indent=2) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='Import a DNS zone file and export to a YAML file') | |
parser.add_argument('-f', '--filename', required=True, help='The DNS zone file to import') | |
parser.add_argument('-e', '--export', required=True, help='Full path to export the YAML file to') | |
parser.add_argument('--ttl', action='store_true', help='Set the TTL for the zone file') | |
parser.add_argument('-t', '--type', nargs='+', help='Type of records to pass to the YAML file') | |
args = parser.parse_args() | |
create_yaml_file(parse_dns_file(args.filename, args.ttl, args.type), args.export) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment