I have written this python script to change the serial number for all DNS zones. The best practice for a DNS zone serial number is to use this template :
YYYYMMDDxx
with :
- YYYY : year
- MM : month
- DD : day
- xx : increment from 01 to 99
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 of the script is :
# ./bind_change_serial_allzones.py -h bind_change_serial_allzones.py -p <zone files path> -s <new serial>
All the zone files are backed up, in the same folder where the dns zone files are located, before the update.
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
Code :
#!/usr/bin/python
import shutil
import re
import sys, getopt
import glob
import os
import time
def main(argv):
pconfpath = ''
serial = ''
try:
opts, args = getopt.getopt(argv,"hp:s:",["pconfpath=","serial="])
except getopt.GetoptError:
print 'bind_change_serial_allzones.py -p <zone files path> -s <new serial>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'bind_change_serial_allzones.py -p <zone files path> -s <new serial>'
sys.exit()
elif opt in ("-p", "--pconfpath"):
pconfpath = arg
elif opt in ("-s", "--serial"):
serial = 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("[0-9]* ; serial",line):
line = '\t\t\t\t' + serial + ' ; serial\n'
f.write(line)
f.close()
if __name__ == "__main__":
main(sys.argv[1:])
Change the serial number for all DNS zones
