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 :

# ./ -h -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 :


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

def main(argv):
        pconfpath = ''
        osoahost = ''
        nsoahost = ''
                opts, args = getopt.getopt(argv,"hp:n:o:",["pconfpath=","nsoahost=","osoahost="])
        except getopt.GetoptError:
                print ' -p <zone files path> -o <old SOA> -n <new SOA>'
        for opt, arg in opts:
                if opt == '-h':
                        print ' -p <zone files path> -o <old SOA> -n <new SOA>'
                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")

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

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

                f = open(dnsfile, 'w')
                for line in lines:
                        if"[a-z. \t]*SOA[a-z. \t]*",line):
                                line = re.sub(r"[\s]*SOA[\s]*" + osoahost, " SOA\t" + nsoahost, line)

if __name__ == "__main__":
Change the SOA in all DNS zone files

Leave a Reply

Your email address will not be published.