2012-02-11 75 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”的下一个地址。