Perl Hacker, Python Initiate

wander.lairson wander.lairson at gmail.com
Wed Feb 2 10:52:02 CET 2011


2011/2/2 Gary Chambers <gwchamb at gwcmail.com>:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
As this is a python list, don't expect people understand Perl code (I
don't know Perl, for example). But I understand, you call the
/usr/bin/dig program and do some text processing on its ouput. Am I
right? If so, you might want to give a look at re and subprocess
modules.

http://docs.python.org/py3k/howto/regex.html
http://docs.python.org/py3k/library/re.html
http://docs.python.org/py3k/library/subprocess.html


-- 
Best Regards,
Wander Lairson Costa
LCoN - Laboratório de Computação Natural - Natural Computing Laboratory
(http://www.mackenzie.com.br/lcon.html)
Programa de Pós-Graduação em Engenharia Elétrica (PPGEE)
Faculdade de Computação e Informática (FCI)
Universidade Presbiteriana Mackenzie - SP - Brazil



More information about the Python-list mailing list