I have written this python code to help me to change the SOA in all of my DNS zone files on my Bind server.
After running this script as shown below, you have to reload your zone file using one of these lines :
Reload all zones : rndc reload
Reload one specific zone : rndc reload domain.local
The following modules are required for this script :
- shutil : used to backup the zone files
- re : regex module
- sys, getopt : used to manage the script parameters
- glob : used to get all dns zone files with the extension .dns
- os : used to work in the folder specified with the parameter “-p”
- time : get datetime and include this information in the backup dns zone filename
Syntax :
# ./bind_change_soa_allzones.py -h bind_remove_nsrecord_allzones.py -p <zone files path> -o <old SOA> -n <new SOA> -p : Path where the dns zone files are located -o : the old SOA hostname > old.domain.local. -n : the new SOA hostname > new.domain.local.
Code :
#!/usr/bin/python import shutil import re import sys, getopt import glob import os import time def main(argv): pconfpath = '' osoahost = '' nsoahost = '' try: opts, args = getopt.getopt(argv,"hp:n:o:",["pconfpath=","nsoahost=","osoahost="]) except getopt.GetoptError: print 'bind_remove_nsrecord_allzones.py -p <zone files path> -o <old SOA> -n <new SOA>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'bind_remove_nsrecord_allzones.py -p <zone files path> -o <old SOA> -n <new SOA>' sys.exit() elif opt in ("-p", "--pconfpath"): pconfpath = arg elif opt in ("-n", "--nsoahost"): nsoahost = arg elif opt in ("-o", "--osoahost"): osoahost = arg #Define variables timestr = time.strftime("%Y%m%d-%H%M%S") os.chdir(pconfpath) for dnsfile in glob.glob("*.dns"): dnsfilebkp = dnsfile + "_" + timestr + ".bkp" shutil.copyfile(dnsfile,dnsfilebkp) f = open(dnsfile, 'r') lines = f.readlines() f.close() f = open(dnsfile, 'w') for line in lines: if re.search("[a-z. \t]*SOA[a-z. \t]*",line): line = re.sub(r"[\s]*SOA[\s]*" + osoahost, " SOA\t" + nsoahost, line) f.write(line) f.close() if __name__ == "__main__": main(sys.argv[1:])
Change the SOA in all DNS zone files