Automagically generate reverse from forward zones

Given a (forward) zone file, here is a quick way to automagically generate all the reverse zone files you need:

#!/usr/bin/perl
#
# does not generate PTR records for $GENERATE lines
# does not generate PTR records for CNAME and AAAA RRs
# generates PTR records for A RRs
#
%revzones = ();
$domain = $ARGV[0] || "irc.gr";
$filter = $ARGV[1] || '\S+';

open (F, "<$domain");
while (<F>) {
	next if ($_ =~ /^[;\#\$]/);
	if ($_ =~ /(\S+)[\s]+(\d+[\s]+)?IN[\s]+A[\s]($filter)/) {
		$host = $1;
		$ip = $3;
		($a, $b, $c, $d) = split (/\./, $ip);
		$revzone = "$c.$b.$a.in-addr.arpa";
		$ptr = "$d\tIN\tPTR\t$host.$domain.\n";
		$revzones{$revzone} .= $ptr;
	}
}
close (F);

open (NC, ">named.conf.rev");
foreach $revzone ( sort keys %revzones ) {
	open (R, ">$revzone");
	print R "\$INCLUDE \"soa-ns.inc\"\n";
	print R "$revzones{$revzone}";
	close (R);
	print NC "zone \"$revzone\" { type master; file \"rev/$revzone\"; };\n";
}
close (NC);

Careful as it will overwrite any existing reverse zone files you have in your current working directory.

PS. I do have one zone that generates 263 reverse zone files!

Advertisement