Skip to content

Instantly share code, notes, and snippets.

@dlage
Forked from andrew-nuwber/README.md
Last active June 2, 2023 20:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dlage/93b880c700081d8c0938978b9253c91b to your computer and use it in GitHub Desktop.
Save dlage/93b880c700081d8c0938978b9253c91b to your computer and use it in GitHub Desktop.
Namecheap DNS to zone file
# Originally by Judotens Budiarto (https://github.com/judotens)
# See: https://gist.github.com/judotens/151341f04b37ffeb5b59
def parse_dns_info(dns_info):
records = dns_info['Result']['CustomHostRecords']['Records']
items = []
record_types = {
1: 'A',
2: 'CNAME',
3: 'MX',
5: 'TXT',
8: 'AAAA'
}
for record in records:
host = str(record['Host'])
if host == '@':
host = domain
else:
host = host + '.' + domain
if record['RecordType'] in record_types.keys():
tipe = record_types[record['RecordType']]
else:
# Skipping unknown record
tipe = 'UNKNOWN'
host = "# Record not identified:\n# " + host
value = str(record['Data'])
ttl = str(record['Ttl'])
priority = str(record['Priority'])
active = record['IsActive']
if not active: continue
new_value = value
if tipe == 'MX': new_value = "%s %s" % (str(priority), str(value))
if tipe == 'TXT': new_value = "\"%s\"" % (str(value))
items.append([host,ttl,"IN", tipe, new_value])
return items
if __name__ == "__main__":
import sys
import json
file_name = sys.argv[1]
try:
file = open(file_name, 'r')
except IOError:
print("File not accessible")
dns_info = json.loads(file.read());
zones = parse_dns_info(dns_info)
for zone in zones:
print "\t".join(zone)
@mbafford
Copy link

Thanks for forking/sharing this - worked great for me, except I had to add:
domain = sys.argv[2]
after the file_name = line.

@ashleykleynhans
Copy link

@mbafford you don't need to provide the domain, its already in the JSON file, you can get it as follows:

domain = dns_info['Result']['DomainBasicDetails']['DomainName']

@ashleykleynhans
Copy link

Thanks for the gist, I've made the following changes:

  1. Added Python 3 support.
  2. Improved error handling.
  3. Support for more types of DNS records.
  4. Refactored code to break out of loops sooner and stop casting everything as a str.
  5. Added argparse to validate command line arguments.
  6. Option to choose either the default or cloudflare output format.
  7. Autodetect domain name from JSON instead of providing it as a command line argument.

https://gist.github.com/ashleykleynhans/69e4fb525d4f32d766313d3f9d22b688

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment