I l@ve RuBoard Previous Section Next Section

9.10 Updating a Zone Programmatically

9.10.1 Problem

You want to dynamically update a zone programmatically.

9.10.2 Solution

I don't want to sound like a broken record, but here's another place where Net::DNS shines. Sending dynamic updates with the C resolver routines is fairly unpleasant. With Net::DNS, it's a breeze. Here's a script that uses dynamic update to add an A record for a host:

#!/usr/bin/perl -w
 
use Net::DNS;
 
# If the user didn't specify the domain name and address of a host to add, exit
die "Usage:  $0 <host> <address>" unless (@ARGV == 2);
 
my $host = $ARGV[0];
my $zone = $host;
my $addr = $ARGV[1];
my $primary;
 
# (Simplemindedly) Derive the domain name of the zone from the domain
# name of the host
$zone =~ s/^[\w-]+\.//;
 
# Create the update message
my $update = Net::DNS::Update->new($zone);
    
# Add an A records for the host
$update->push("update", rr_add("$host. 86400 A $addr"));
# Find the zone's primary master name server
my $res = Net::DNS::Resolver->new;
my $query = $res->query($zone, "SOA");
 
if ($query) {
        $primary = ($query->answer)[0]->mname;
} else {
        die "Couldn't find primary master name server: ", $res->errorstring, "\n
";
}
 
$res->nameservers($primary);
    
my $reply = $res->send($update);
    
# Did it work?
if (defined $reply) {
        if ($reply->header->rcode eq "NOERROR") {
                print "Update succeeded\n";
        } else {
                print "Update failed: ", $reply->header->rcode, "\n";
        }
}

9.10.3 Discussion

As with the scripts in Recipes Section 9.8 and Section 9.9, this script doesn't do much input or error checking. Also, it could be more flexible: it could allow you to specify the TTL for the A record, and it could find the domain name of the zone to update by stripping off the labels of the domain name until it finds an SOA record, instead of just removing the first label and calling it a day.

Authorizing dynamic updates is a particularly apt use of TSIG. For help with signing dynamic updates with TSIG, see Section 9.11.

9.10.4 See Also

Section 5.20 for instructions on using nsupdate to send dynamic updates; Section 9.11 for sending TSIG-signed dynamic updates programmatically.

    I l@ve RuBoard Previous Section Next Section