During migration it's sometimes useful to test a server with many virtual hosts before directing them to their new IP. For this purpose it's necessary to have a proper hosts file on the testing station. The following bash/awk script reads and parses bind9 configuration from an OpenVZ virtualized ROOT directory (can be substituted as /
for non-virtualized environments), then converts zone A records to a suitable hosts file format (IPADDR FQDN). The output can be then copied into /etc/hosts
or C:\WINDOWS\SYSTEM32\DRIVERS\ETC\HOSTS
files respectively.
#!/bin/bash ROOT=/var/lib/vz/root/1000/ bindconf=$ROOT/etc/bind/named.conf OLDIP=1.2.3.4 NEWIP=5.6.7.8 dumpbindconf() { awk -v ROOT=$ROOT ' {rinclude($0)} function rinclude(line,x,a) { sub(/^#/,"",line); # strip leading comments split(line,a,/ /); if ( a[1] ~ /^[ ]*include/ ) { #looking for =include at start of line file=ROOT a[2] gsub(/[\";]/,"",file) print ";------ INCLUDE " file while ( ( getline x < file ) > 0) rinclude(x);. close(a[2])} else {print line} } ' } dumpzones() { awk -v ROOT=$ROOT ' /^[ ]*zone/ {. zone=$2 gsub(/[\";]/,"",zone) } /^[ \t]*file/ { file=$2 gsub(/[\";]/,"",file) file=ROOT file print "; zone file for " zone gethosts(file) } function gethosts(file) { while ( ( getline x < file ) > 0 ) print x; close(file) } ' } dumptohosts() { awk ' /^; zone file for/ {. zone=$5 gsub(/[\";]/,"",zone) #print zone } /^.*@.*IN.*A.*[0-9]+/ { print $4 " " zone } /^[^@]*IN.*A.*[0-9]+/ { print $4 " " $1 "." zone } ' } cat "$bindconf" | dumpbindconf | dumpzones | dumptohosts | grep "$OLDIP" | sed "s/$OLDIP/$NEWIP/g"