2012-02-11 46 views
3

因此,在otter book中,有一個小腳本(參見第173頁),其目的是迭代檢查DNS服務器以查看它們是否爲給定主機名返回相同地址。但是,本書中給出的解決方案僅在主機具有靜態IP地址時才起作用。如果我希望它能與具有多個地址關聯的主機一起工作,我該如何編寫此腳本?使用perl和Net :: DNS進行DNS檢查

下面是代碼:

#!/usr/bin/perl 
use Data::Dumper; 
use Net::DNS; 

my $hostname = $ARGV[0]; 
# servers to check 
my @servers = qw(8.8.8.8 208.67.220.220 8.8.4.4); 

my %results; 
foreach my $server (@servers) { 
    $results{$server} 
     = lookup($hostname, $server); 
} 

my %inv = reverse %results; # invert results - it should have one key if all 
          # are the same 
if (scalar keys %inv > 1) { # if it has more than one key 
    print "The results are different:\n"; 
    print Data::Dumper->Dump([ \%results ], ['results']), "\n"; 
} 

sub lookup { 
    my ($hostname, $server) = @_; 

    my $res = new Net::DNS::Resolver; 
    $res->nameservers($server); 
    my $packet = $res->query($hostname); 

    if (!$packet) { 
     warn "$server not returning any data for $hostname!\n"; 
     return; 
    } 
    my (@results); 
    foreach my $rr ($packet->answer) { 
     push (@results, $rr->address); 
    } 
    return join(', ', sort @results); 
} 

回答

0

我的問題是,我得到這個錯誤調用一個返回多個地址,比如www.google.com主機名代碼:

*** WARNING!!! The program has attempted to call the method 
*** "address" for the following RR object: 
*** 
*** www.google.com. 86399 IN CNAME www.l.google.com. 
*** 
*** This object does not have a method "address". THIS IS A BUG 
*** IN THE CALLING SOFTWARE, which has incorrectly assumed that 
*** the object would be of a particular type. The calling 
*** software should check the type of each RR object before 
*** calling any of its methods. 
*** 
*** Net::DNS has returned undef to the caller. 

這個錯誤意味着我試圖在CNAME類型的rr對象上調用地址方法。我只想在'A'類型的rr對象上調用地址方法。在上面的代碼中,我沒有檢查以確保我在「A」類型的對象上調用地址。我加入這行代碼(在下除非),以及它的工作原理:

my (@results); 
foreach my $rr ($packet->answer) { 
    next unless $rr->type eq "A"; 
    push (@results, $rr->address); 
} 

這行代碼跳到從$packet->answer得到,除非RR對象的類型爲「A」的下一個地址。