Perl Hacker, Python Initiate

waku waku at idi.ntnu.no
Thu Feb 3 11:18:44 EST 2011


you've already got a hint on how to do it using library functions in
python.  below is a more literal suggestion.

On Feb 1, 10:36 pm, Gary Chambers <gwch... at gwcmail.com> wrote:
> All,
>
> Given the following Perl script:
>
> #!/usr/bin/perl
>
> %dig = (
>      solaris => "/usr/sbin/dig",
>      linux   => "/usr/bin/dig",
>      darwin  => "/usr/bin/dig"
> );


dig = {"solaris":"/usr/sbin/dig", "linux":"/usr/bin/dig", "darwin":"/
usr/bin/dig"}


>
> $DIG = $dig{"$^O"};

dig = dig[os.uname()[0].lower()]


> $DOMAIN = "example.com";
> $DNS = "ns.example.com";

domain, dns = ['%sexample.com'%p for p in ('', 'ns.')] # ;)

> $DIGCMD = qq/$DIG \@$DNS $DOMAIN axfr/;

digcmd = '%s @%s %s axfr' % (dig, dns, domain)

>
> 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;

lines = [line for line in os.popen(digcmd) if not re.match(';', line)]
cname, ip = [re.compile(s.format(domain))
    for s in (r'(\S+)\.{0}\.\s+\d+\s+IN\s*CNAME\s+(\S+)\.{0}\.$', r'(\S
+)\.{0}\.\s+\d+\s+IN\s*A\s+(\S+)$')]
cnames, ips = [dict(m.groups() for m in (p.match(l) for l in lines) if
m) for p in cname, ip)]

the rest is left as an exercise.  i did not test this exact code
because i don't have your data, but a modified version works on
different data.

vQ

>
> # 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