bind9I have written this python code to remove a NS record in all DNS zone files on my Bind server.

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

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 syntax is :

# ./bind_remove_nsrecord_allzones.py -h
bind_remove_nsrecord_allzones.py -p <zone files path> -n <NS record to remove>

Code :

#!/usr/bin/python

import shutil
import re
import sys, getopt
import glob
import os
import time

def main(argv):
        pconfpath = ''
        nshost = ''
        try:
                opts, args = getopt.getopt(argv,"hp:n:",["pconfpath=","nshost="])
        except getopt.GetoptError:
                print 'bind_remove_nsrecord_allzones.py -p <zone files path> -n <NS record to remove>'
                sys.exit(2)
        for opt, arg in opts:
                if opt == '-h':
                        print 'bind_remove_nsrecord_allzones.py -p <zone files path> -n <NS record to remove>'
                        sys.exit()
                elif opt in ("-p", "--pconfpath"):
                        pconfpath = arg
                elif opt in ("-n", "--nshost"):
                        nshost = arg

        #Define variables
        timestr = time.strftime("%Y%m%d-%H%M%S")

        os.chdir(pconfpath)
        for dnsfile in glob.glob("*.dns"):
                print(dnsfile)
                dnsfilebkp = dnsfile + "_" + timestr + ".bkp"
                shutil.copyfile(dnsfile,dnsfilebkp)

                #Regex to get the lines containing the master ip address for the zone
                regexp = re.compile("[\s]*NS[\s]*" + nshost )

                f = open(dnsfile, 'r')
                lines = f.readlines()
                f.close()

                f = open(dnsfile, 'w')
                for line in lines:
                        if re.match(regexp, line) is None:
                            f.write(line)
                f.close()

if __name__ == "__main__":
        main(sys.argv[1:])
Remove a NS record in all DNS zone files

Leave a Reply

Your email address will not be published. Required fields are marked *