Perl Hacker, Python Initiate

Gary Chambers gwchamb at gwcmail.com
Tue Feb 1 23:36:27 EST 2011


All,

Given the following Perl script:

#!/usr/bin/perl

%dig = (
     solaris => "/usr/sbin/dig",
     linux   => "/usr/bin/dig",
     darwin  => "/usr/bin/dig"
);

$DIG = $dig{"$^O"};
$DOMAIN = "example.com";
$DNS = "ns.example.com";
$DIGCMD = qq/$DIG \@$DNS $DOMAIN axfr/;

open DIG, "$DIGCMD|" or die "$DIG: $!\n";
while (<DIG>) {
     next if (/^;/); # Skip any comments
     # If we match a CNAME record, we have an alias to something.
     # $1 = alias (CNAME), $2 = canonical hostname
     if (/^(\S+)\.${DOMAIN}\.\s+\d+\s+IN\s*CNAME\s+(\S+)\.${DOMAIN}\.$/) {
         # Push an alias (CNAME) onto an array indexed on canonical hostname
         push(@{$cnames{$2}}, $1);
     }
     # Here's a standard A (canonical hostname) record
     # $1 = canonical hostname, $2 = IPv4 address
     if (/^(\S+)\.${DOMAIN}\.\s+\d+\s+IN\s*A\s+(\S+)$/) {
         $ip{$1} = $2;
     }
}
close DIG;

# Format and display it like niscat hosts:
# canonicalHostname alias1 [alias2 aliasN] ipAddress
for $host (sort keys %ip) {
     print "$host ";
     if (defined(@{$cnames{$host}})) {
         print join(' ', @{$cnames{$host}});
         print " ";
     }
     print "$ip{$host}\n";
}
exit 0;

Will someone please provide some insight on how to accomplish that task in
Python?  I am unable to continually (i.e. it stops after displaying a single
line) loop through the output while testing for the matches on the two
regular expressions.  Thank you.

-- Gary Chambers



More information about the Python-list mailing list