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 :

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

Code :


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

def main(argv):
        pconfpath = ''
        nshost = ''
                opts, args = getopt.getopt(argv,"hp:n:",["pconfpath=","nshost="])
        except getopt.GetoptError:
                print ' -p <zone files path> -n <NS record to remove>'
        for opt, arg in opts:
                if opt == '-h':
                        print ' -p <zone files path> -n <NS record to remove>'
                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")

        for dnsfile in glob.glob("*.dns"):
                dnsfilebkp = dnsfile + "_" + timestr + ".bkp"

                #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 = open(dnsfile, 'w')
                for line in lines:
                        if re.match(regexp, line) is None:

if __name__ == "__main__":
Remove a NS record in all DNS zone files

Leave a Reply

Your email address will not be published.