<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: perl code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Mon, 12 May 2008 03:28:54 GMT</pubDate>
    <description>DZone Snippets: perl code</description>
    <item>
      <title>Perl : scan a list of networks, looking for hosts responding on the port 80 (http)</title>
      <link>http://snippets.dzone.com/posts/show/5467</link>
      <description>// Input : a list of address of routers, in dotted decimal notation&lt;br /&gt;&lt;code&gt;&lt;br /&gt;use strict;&lt;br /&gt;use Net::Ping;&lt;br /&gt;use IO::Socket::INET;&lt;br /&gt;&lt;br /&gt;sub isodate() {&lt;br /&gt;        my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];&lt;br /&gt;        $mon++; # 0-based index&lt;br /&gt;        $year = $year + 1900;&lt;br /&gt;        my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);&lt;br /&gt;        return $date;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;sub testhost {&lt;br /&gt;       my $p = new Net::Ping("tcp");&lt;br /&gt;       $p-&gt;{port_num}=80; &lt;br /&gt;       my @result = $p -&gt; ping($_[0],2);&lt;br /&gt;       return $result[0];&lt;br /&gt;       }&lt;br /&gt;&lt;br /&gt;sub to_dot {&lt;br /&gt;	my $n = shift;&lt;br /&gt;	my @decimal;&lt;br /&gt;	for (1..4) {&lt;br /&gt;		unshift @decimal, $n &amp; 0xFF;&lt;br /&gt;		$n &gt;&gt;= 8;&lt;br /&gt;	}&lt;br /&gt;	return join(".",@decimal);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;my %dejavu;&lt;br /&gt;open FH,"liste.txt";&lt;br /&gt;while (&lt;FH&gt;) {&lt;br /&gt;	chomp;&lt;br /&gt;	my ($routeur,$mask)=split;&lt;br /&gt;	&lt;br /&gt;	next if $routeur !~ /\d+\.\d+\.\d+\.\d+$/ or $mask !~ /\d+\.\d+\.\d+\.\d+$/;&lt;br /&gt;	&lt;br /&gt;	next if defined($dejavu{$routeur});&lt;br /&gt;	$dejavu{$routeur}=1;&lt;br /&gt;	&lt;br /&gt;	my ($o1,$o2,$o3,$o4) = split /\./,$mask;&lt;br /&gt;	my $mask=$o1*256**3+$o2*256**2+$o3*256+$o4;&lt;br /&gt;	my $num = $mask ^ 0xFFFFFFFF;&lt;br /&gt;	$num--;&lt;br /&gt;&lt;br /&gt;	my ($o1,$o2,$o3,$o4) = split /\./,$routeur;&lt;br /&gt;	my $net=$o1*256**3+$o2*256**2+$o3*256+$o4 &amp; $mask;&lt;br /&gt;	&lt;br /&gt;	#print join("|",$routeur,&amp;to_dot($net),$num)."\n";&lt;br /&gt;	&lt;br /&gt;	print "Starting scanning network ".to_dot($net).", router = ".$routeur."\n";&lt;br /&gt;	print "Adresses demarrant de ".to_dot($net+1)." et finissant a ".to_dot($net+$num).".\n";&lt;br /&gt;	for my $i (1..$num) {&lt;br /&gt;		my $host=to_dot($net+$i);&lt;br /&gt;		if ( &amp;testhost($host) ) {&lt;br /&gt;			print "$host is alive\n";&lt;br /&gt;			my $port=80;&lt;br /&gt;			my $sock = new IO::Socket::INET (PeerAddr =&gt; $host,&lt;br /&gt;					     PeerPort =&gt; $port,&lt;br /&gt;					     Proto =&gt; 'tcp');&lt;br /&gt;			if ($sock){&lt;br /&gt;				close $sock;&lt;br /&gt;				print "$port -open on $host\n";&lt;br /&gt;				open OUT,"&gt;&gt;webservers.txt";&lt;br /&gt;				print OUT join("|",isodate(),$host,to_dot($net),$routeur)."\n";&lt;br /&gt;				close OUT;&lt;br /&gt;			}	else	{&lt;br /&gt;				print "$port -closed on $host\n";&lt;br /&gt;			}&lt;br /&gt;&lt;br /&gt;		} else {&lt;br /&gt;			print "$host is not responding\n";&lt;br /&gt;		}&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;close FH;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 06 May 2008 07:05:28 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5467</guid>
      <author>bouffon69 (Sylvain Le Courtois)</author>
    </item>
    <item>
      <title>Bashy Perlness for generating Favicon text for OpenSearches</title>
      <link>http://snippets.dzone.com/posts/show/5418</link>
      <description>&lt;code&gt;&lt;br /&gt;echo -n '&lt;Image width="16" height="16"&gt;data:image/xicon,' ; perl -ne 's/(.)/"%".unpack("H2",$1)/egs; print' ~/Desktop/favicon.ico ; echo '&lt;/Image&gt;' &lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 21 Apr 2008 19:58:49 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5418</guid>
      <author>sikelianos (Zeke Sikelianos)</author>
    </item>
    <item>
      <title>Retrieve Cisco router traffic statistics using perl and RRDTOOL and PHP</title>
      <link>http://snippets.dzone.com/posts/show/5287</link>
      <description>Traffic retrieving perl script:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;    #!/opt/csw/bin/perl -w&lt;br /&gt;    ##################################################&lt;br /&gt;    # rrdtraf.pl&lt;br /&gt;    #&lt;br /&gt;    # Trafego de equipamentos Cisco&lt;br /&gt;    #&lt;br /&gt;    # 2006.01.12 - Adriano P. &lt;br /&gt;    # $Id: $&lt;br /&gt;&lt;br /&gt;    ######################&lt;br /&gt;    require 5.003;&lt;br /&gt;    use strict;&lt;br /&gt;    use SNMP_Session;&lt;br /&gt;    use BER;&lt;br /&gt;    use SNMP_util "0.90";&lt;br /&gt;    use Time::Local;&lt;br /&gt;    use RRDs;&lt;br /&gt;    use Getopt::Long;&lt;br /&gt;    use Pod::Usage;&lt;br /&gt;&lt;br /&gt;    ##### GLOBAL #####&lt;br /&gt;    my %opt;&lt;br /&gt;    my @routers;&lt;br /&gt;    my $IP_APPEND="::2:2";&lt;br /&gt;    my $ERROR;&lt;br /&gt;    my %rrd;&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub main {&lt;br /&gt;    init();&lt;br /&gt;&lt;br /&gt;    Options(%opt);&lt;br /&gt;&lt;br /&gt;    open(PAR, "rrdtraf.par") || die "Problema ao abrir rrdtraf.parn";&lt;br /&gt;&lt;br /&gt;    Msg("* Coletando dados dos switches");&lt;br /&gt;    while () {&lt;br /&gt;    next if grep(/^(#)/,$_);&lt;br /&gt;&lt;br /&gt;    my ($community,$ip,$net,@if) = split /:/;&lt;br /&gt;    #$ip = "${community}@${ip}"; #host:port:timeout:retries&lt;br /&gt;&lt;br /&gt;    LeituraSNMP($community, $ip,@if);&lt;br /&gt;&lt;br /&gt;    syswrite(STDOUT,'.',1) if (!$opt{verbose} &amp;&amp; !$opt{V});&lt;br /&gt;    }&lt;br /&gt;    close(PAR);&lt;br /&gt;    Msg("n","* Fim");&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    main;&lt;br /&gt;    exit 0;&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub CriaRRD($) {&lt;br /&gt;    my $arquivo = shift;&lt;br /&gt;&lt;br /&gt;    print "- Criando base de dados:($arquivo) - " if $opt{verbose};&lt;br /&gt;&lt;br /&gt;    RRDs::create ("$arquivo", "--start", time(),&lt;br /&gt;    "--step", "300",&lt;br /&gt;    "DS:ifInOctets:COUNTER:600:0:U",&lt;br /&gt;    "DS:ifOutOctets:COUNTER:600:0:U",&lt;br /&gt;    "RRA:AVERAGE:0.5:1:600",    #2 dias, com amostra de 5min&lt;br /&gt;    "RRA:AVERAGE:0.5:6:700",    #2 semanas, com amostra de 30min&lt;br /&gt;    "RRA:AVERAGE:0.5:24:775",    #2 meses, com amostra de 2h&lt;br /&gt;    "RRA:AVERAGE:0.5:288:400");    #1 ano, com amostra de 1 dia&lt;br /&gt;    if ($ERROR = RRDs::error) {&lt;br /&gt;    die "$0: unable to graph $arquivo: $ERRORn";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    print "okn" if $opt{verbose};&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub LeituraSNMP($$$) {&lt;br /&gt;    my $community = shift;&lt;br /&gt;    my $ip = shift;&lt;br /&gt;    my (@if) = @_;&lt;br /&gt;&lt;br /&gt;    my ($idx, $arquivo);&lt;br /&gt;    my $ifInBroadcastPkts = "1.3.6.1.2.1.2.2.1.12";&lt;br /&gt;    my $ifOutBroadcastPkts = "1.3.6.1.2.1.2.2.1.18";&lt;br /&gt;    my @oids = ('ifIndex','ifDescr','ifInOctets','ifOutOctets');&lt;br /&gt;&lt;br /&gt;    my @stack = &amp;SNMP("${community}@${ip}", @oids);&lt;br /&gt;    #$ip =~ s/.*@//;&lt;br /&gt;&lt;br /&gt;    print "--[ $ip ]-----------n" if $opt{verbose};&lt;br /&gt;&lt;br /&gt;    foreach $idx (@stack) {&lt;br /&gt;    my ($id,$nome) = SNMP_util::Check_OID('ifDescr');&lt;br /&gt;    next if (!${$idx}{$id});&lt;br /&gt;    # Ignora interfaces nao cadastradas&lt;br /&gt;    if( !grep(/^${$idx}{$id}$/,@if) ) {&lt;br /&gt;    next;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    my @dados = ();&lt;br /&gt;    $dados[0] = $ip;                # 1: ip&lt;br /&gt;    @dados[1,2,3,4] = &amp;Dados($idx,@oids);&lt;br /&gt;    my $ifIndex = $dados[1];&lt;br /&gt;&lt;br /&gt;    $arquivo = "${ip}_${ifIndex}.rrd";&lt;br /&gt;    if (! -e "$arquivo") {&lt;br /&gt;    CriaRRD($arquivo);&lt;br /&gt;    }&lt;br /&gt;    AtualizaRRD($arquivo, @dados);&lt;br /&gt;    }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub AtualizaRRD(@) {&lt;br /&gt;    my $arquivo = shift;&lt;br /&gt;    my (@dados) = @_;&lt;br /&gt;&lt;br /&gt;    print "- $dados[0], $dados[1], $dados[2], $dados[3], $dados[4]n" if $opt{verbose};&lt;br /&gt;&lt;br /&gt;    RRDs::update ($arquivo, "N:$dados[3]:$dados[4]");&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub GrafRRD {&lt;br /&gt;    my ($start_date,$eqto) = @_;&lt;br /&gt;&lt;br /&gt;    print "Gerando grafico ($start_date)...";&lt;br /&gt;&lt;br /&gt;    my @option = ("-s", $start_date, "-w", "600", "-h", "170",&lt;br /&gt;    "-e", "now", "--alt-autoscale", "-l 0",&lt;br /&gt;    "-x", "HOUR:1:DAY:1:HOUR:2:0:%H");&lt;br /&gt;&lt;br /&gt;    if ($start_date &gt;= 2) {&lt;br /&gt;&lt;br /&gt;    ######################&lt;br /&gt;    # GRAPH 1&lt;br /&gt;    RRDs::graph ("$eqto.gif", @option,&lt;br /&gt;    "DEF:in=$eqto.gif:ifInOctets:AVERAGE",&lt;br /&gt;    "DEF:out=$eqto.gif:ifOutOctets:AVERAGE",&lt;br /&gt;    "LINE2:c13#0000aa:Entrada",&lt;br /&gt;    "LINE2:c14#ff66ff:Saida");&lt;br /&gt;    if ($ERROR = RRDs::error) {&lt;br /&gt;    die "$0: unable to graph $eqto.gif: $ERRORn";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    print "okn";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub SNMP($@) {&lt;br /&gt;    my $ip = shift;&lt;br /&gt;    my @oids = @_;&lt;br /&gt;&lt;br /&gt;    my $ip_="$ip${IP_APPEND}";&lt;br /&gt;    my ($idx,$oid,@stack);&lt;br /&gt;&lt;br /&gt;    foreach my $tuple (snmpwalk($ip_, @oids)) {&lt;br /&gt;    my($var,$counter) = split /:/, $tuple, 2;&lt;br /&gt;    $idx = substr($var, rindex($var,'.')+1);&lt;br /&gt;    $oid = substr($var, 0, length($var)-length($idx)-1);&lt;br /&gt;    #warn "* $vart$countern" if $opt{V};&lt;br /&gt;    $stack[$idx]{$oid} = $counter;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return @stack;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub Dados($$) {&lt;br /&gt;    my $var = shift;&lt;br /&gt;    my @oids = @_;&lt;br /&gt;&lt;br /&gt;    my @dados = ();&lt;br /&gt;&lt;br /&gt;    for(my $i=0; $i  2) if $$opt{man};&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    ##################################################################&lt;br /&gt;    sub init {&lt;br /&gt;    # queue up reading the MIB file&lt;br /&gt;    #&amp;snmpQueue_MIB_File("/home/adr/mibs/IWFG.MIB");&lt;br /&gt;    $SNMP_Session::suppress_warnings = 2;&lt;br /&gt;    $SNMP_util::Debug = 0;&lt;br /&gt;    $= = 1000;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    #eof&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;rrdtraf.par - sample file&lt;br /&gt;&lt;code&gt;&lt;br /&gt;    community:10.1.2.3:Comment:FastEthernet0/1:FastEthernet0/2&lt;br /&gt;    community:10.1.2.4:Comment:FastEthernet0/1&lt;br /&gt;    community:10.1.2.5:Comment:FastEthernet0/1:FastEthernet0/2:FastEthernet0/12:FastEthernet0/18&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;PHP script to plot the traffic graph:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;    {!--&lt;br /&gt;    ##################################################&lt;br /&gt;    # rrdgraph.php&lt;br /&gt;    #&lt;br /&gt;    # Plotagem dos graficos de arquivos rrd&lt;br /&gt;    #&lt;br /&gt;    # 2006.01.12 - Adriano P.&lt;br /&gt;    # $Id: $&lt;br /&gt;    --}&lt;br /&gt;    {?php&lt;br /&gt;    $display = $_GET['display'];&lt;br /&gt;&lt;br /&gt;    if ($display == 'image') {&lt;br /&gt;&lt;br /&gt;    header ("Content-type: image/png",false);&lt;br /&gt;&lt;br /&gt;    $display = $_GET['display'];&lt;br /&gt;    $rrdtool = "/opt/csw/bin/rrdtool ";&lt;br /&gt;    $graph_opt =     "--height 150 --width 550 " .&lt;br /&gt;    "--start -172800 ".&lt;br /&gt;    "--imgformat PNG ".&lt;br /&gt;    "--no-minor ".&lt;br /&gt;    "-c BACK#ffffff ".&lt;br /&gt;    "-c SHADEA#ffffff ".&lt;br /&gt;    "-c SHADEB#ffffff ".&lt;br /&gt;    "-c FRAME#ffffff ".&lt;br /&gt;    "-v 'bits/seg' -L 8  ";&lt;br /&gt;&lt;br /&gt;    $arq1="/home/aprado/proj/traf/".$_GET['arq1'];&lt;br /&gt;&lt;br /&gt;    $graph =&lt;br /&gt;    "DEF:in1=$arq1:ifInOctets:AVERAGE ".&lt;br /&gt;    "DEF:out1=$arq1:ifOutOctets:AVERAGE ".&lt;br /&gt;    "CDEF:in1_bps=in1,8,* ".   #N&#195;O ESQUECER DE MULTIPLICAR POR 8&lt;br /&gt;    "CDEF:out1_bps=out1,8,* ".  #(1 byte = 8 bits)&lt;br /&gt;    "HRULE:0#000000:'       ' ".&lt;br /&gt;    "AREA:in1_bps#6699cc:'Saida' ".&lt;br /&gt;    "LINE2:out1_bps#003399:'Entrada' ";&lt;br /&gt;&lt;br /&gt;    # function for rrdtool execution&lt;br /&gt;    function rrdtool_execute($rrdtool, $command) {&lt;br /&gt;    return fpassthru(popen($rrdtool . $command, "r"));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    $command = $graph_opt . $graph;&lt;br /&gt;    return rrdtool_execute($rrdtool, " graph - $command");&lt;br /&gt;    }&lt;br /&gt;    ?}&lt;br /&gt;&lt;br /&gt;    {HTML}&lt;br /&gt;    {HEAD}&lt;br /&gt;    {STYLE TYPE="text/css"}&lt;br /&gt;    H1 {&lt;br /&gt;    font-weight: bold;&lt;br /&gt;    font-size: 18pt;&lt;br /&gt;    line-height: 18pt;&lt;br /&gt;    font-family: arial,helvetica;&lt;br /&gt;    font-variant: normal;&lt;br /&gt;    font-style: normal;&lt;br /&gt;    }&lt;br /&gt;    BODY {&lt;br /&gt;    color: black;&lt;br /&gt;    background-color: white;&lt;br /&gt;    font-size: 11pt;&lt;br /&gt;    line-height: 12pt;&lt;br /&gt;    font-family: arial,helvetica;&lt;br /&gt;    font-variant: normal;&lt;br /&gt;    font-style: normal;&lt;br /&gt;    }&lt;br /&gt;    {/STYLE}&lt;br /&gt;    {/HEAD}&lt;br /&gt;    {BODY}&lt;br /&gt;&lt;br /&gt;    {CENTER}&lt;br /&gt;    {TABLE}&lt;br /&gt;    {?php&lt;br /&gt;&lt;br /&gt;    function graphit($arq1, $descr1) {&lt;br /&gt;    print "{tr align='center'}{td}{font color='#003399'}{b}$descr1{/b}{/font}{br}n";&lt;br /&gt;    print "{/td}{/tr}n";&lt;br /&gt;    print "{tr}{td align='center'}{img xsrc='/traf/rrdgraph.php?display=image&amp;arq1=$arq1' border='0'}";&lt;br /&gt;    print "{hr width='100%' size='2'}{/td}{/tr}n";&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    graphit("10.1.2.3_2.rrd","10.1.2.3 - f0/1: Comentario");&lt;br /&gt;    graphit("10.1.2.3_3.rrd","10.1.2.3 - f0/2: Comentario");&lt;br /&gt;&lt;br /&gt;    ?}&lt;br /&gt;    {/TABLE}&lt;br /&gt;    {/CENTER}&lt;br /&gt;    {/BODY}&lt;br /&gt;    {/HTML}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Fri, 28 Mar 2008 20:38:22 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5287</guid>
      <author>adr1an0 (Adr)</author>
    </item>
    <item>
      <title>Split Apache logs according to GeoIP country</title>
      <link>http://snippets.dzone.com/posts/show/5255</link>
      <description>// Split Apache logs according to GeoIP country&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/perl&lt;br /&gt;&lt;br /&gt;# $Id$&lt;br /&gt;&lt;br /&gt;# Split Apache logs according to GeoIP country&lt;br /&gt;&lt;br /&gt;use strict;&lt;br /&gt;use warnings;&lt;br /&gt;&lt;br /&gt;## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)&lt;br /&gt;our ($VERSION) = '$Revision$' =~ m{ \$Revision: \s+ (\S+) }xms;&lt;br /&gt;## use critic&lt;br /&gt;&lt;br /&gt;use Geo::IP;&lt;br /&gt;&lt;br /&gt;my $gi = Geo::IP-&gt;open('/usr/local/share/GeoIP/GeoIPCity.dat', GEOIP_STANDARD);&lt;br /&gt;&lt;br /&gt;my @logs = @ARGV;&lt;br /&gt;&lt;br /&gt;my %record_for;&lt;br /&gt;&lt;br /&gt;foreach my $log (@logs) {&lt;br /&gt;    die "Can't read $log\n" if !-r $log;&lt;br /&gt;    &lt;br /&gt;    my %fh_for;&lt;br /&gt;    my $num_lines_parsed = 0;&lt;br /&gt;    &lt;br /&gt;    my $log_fh;&lt;br /&gt;    if ($log =~ m/ \.gz \z /xms) {&lt;br /&gt;        open $log_fh, "gzip -cd $log |" or die "Can't open gzip pipe\n";&lt;br /&gt;    }&lt;br /&gt;    else {&lt;br /&gt;        open $log_fh, '&lt;', $log or die "Can't open $log\n";&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    my $log_base = $log;&lt;br /&gt;    $log_base =~ s/ \.gz \z //xms;&lt;br /&gt;    &lt;br /&gt;    while (my $line = &lt;$log_fh&gt;) {&lt;br /&gt;        $num_lines_parsed++;&lt;br /&gt;        if (!($num_lines_parsed % 1000)) {&lt;br /&gt;            print STDERR "Parsed $num_lines_parsed lines of $log\n";&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        my ($host) = $line =~ m/ \A (\S+) \s /xms;&lt;br /&gt;        &lt;br /&gt;        if (!exists $record_for{$host}) {&lt;br /&gt;            my $record = $gi-&gt;record_by_name($host);&lt;br /&gt;            $record_for{$host} = $record || 0;&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        my $country = 'unknown';&lt;br /&gt;        if (exists $record_for{$host} &amp;&amp; $record_for{$host}) {&lt;br /&gt;            $country = lc($record_for{$host}-&gt;country_name());&lt;br /&gt;            $country =~ s/\W+/_/gxms;&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        if (!exists $fh_for{$country}) {&lt;br /&gt;            open $fh_for{$country}, '&gt;', "$log_base.$country.out"&lt;br /&gt;                or die "Can't write to $log_base.$country.out\n";&lt;br /&gt;        }&lt;br /&gt;        &lt;br /&gt;        print {$fh_for{$country}} $line;&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    foreach my $fh (values %fh_for) {&lt;br /&gt;        close $fh;&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    close $log_fh;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 19 Mar 2008 15:02:26 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5255</guid>
      <author>iansealy (Ian Sealy)</author>
    </item>
    <item>
      <title>Rapleaf Address Book API in Perl</title>
      <link>http://snippets.dzone.com/posts/show/5232</link>
      <description>Retrieve e-mail contacts from several services using the Rapleaf Address Book API.&lt;br /&gt;&lt;br /&gt;It accesses the Rapleaf API Web server and executes a request to retrieve the contact list of a given user of either Gmail, Yahoo, Hotmail and AOL.&lt;br /&gt;&lt;br /&gt;Returns an associative array with the contacts names and e-mail addresses, as well the HTTP response status and any errors.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;package Rapleaf;&lt;br /&gt;use strict;&lt;br /&gt;&lt;br /&gt;use LWP::UserAgent;&lt;br /&gt;use HTTP::Request;&lt;br /&gt;use XML::Simple;&lt;br /&gt;&lt;br /&gt;sub getData {&lt;br /&gt;	my ($email, $pass, $api_key, $url) = @_;&lt;br /&gt;	my $post_data = "login=$email&amp;password=$pass";&lt;br /&gt;&lt;br /&gt;	$url ||= 'http://api.rapleaf.com/v2/abook';&lt;br /&gt;	my $agent = LWP::UserAgent-&gt;new();&lt;br /&gt;	my $request = HTTP::Request-&gt;new(POST =&gt; $url);&lt;br /&gt;	$request-&gt;content($post_data);&lt;br /&gt;	$request-&gt;header( 'Authorization' =&gt; $api_key );&lt;br /&gt;	my $response;&lt;br /&gt;	$response = $agent-&gt;request($request);&lt;br /&gt;	my %result; &lt;br /&gt;	if($response-&gt;code == 200) {&lt;br /&gt;		my $xml = new XML::Simple;&lt;br /&gt;		%result = %{$xml-&gt;XMLin($response-&gt;content)};&lt;br /&gt;&lt;br /&gt;		# if a single contact if found, XMLin returns a result set of a different format, therefore we need to manually format it&lt;br /&gt;		if ($result{'contact'}-&gt;{'name'}) {&lt;br /&gt;			$result{'contact'}-&gt;{$result{'contact'}-&gt;{'name'}} &lt;br /&gt;				= {'email'=&gt;$result{'contact'}-&gt;{'email'}};&lt;br /&gt;			delete $result{'contact'}-&gt;{'name'};&lt;br /&gt;			delete $result{'contact'}-&gt;{'email'};&lt;br /&gt;		} &lt;br /&gt;	} elsif ($response-&gt;code == 400) {&lt;br /&gt;		$result{'error'} = 'The request did not contain all required parameters: '.$response;&lt;br /&gt;	} elsif ($response-&gt;code == 401) {&lt;br /&gt;		$result{'error'} = 'API key was not provided or is invalid.';&lt;br /&gt;	} elsif ($response-&gt;code == 420) {&lt;br /&gt;		$result{'error'} = 'Login failed.';&lt;br /&gt;	} elsif ($response-&gt;code == 500) {&lt;br /&gt;		$result{'error'} = 'There was an unexpected error on our server. This should be very rare and if you see it please contact developer@rapleaf.com.';&lt;br /&gt;	} elsif ($response-&gt;code == 520) {&lt;br /&gt;		$result{'error'} = 'There was an error while reading the contacts from the address book.';&lt;br /&gt;	}&lt;br /&gt;	&lt;br /&gt;	$result{'status'} = $response-&gt;code;&lt;br /&gt;	return \%result;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;1;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 14 Mar 2008 14:39:58 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5232</guid>
      <author>dannymo2 (Dan Scudder)</author>
    </item>
    <item>
      <title>howmany</title>
      <link>http://snippets.dzone.com/posts/show/5211</link>
      <description>&lt;code&gt;&lt;br /&gt;#!/usr/bin/perl&lt;br /&gt;#==========================================================================================&lt;br /&gt;# howmany -- a tool for determining how many different types of files are in a folder&lt;br /&gt;#------------------------------------------------------------------------------------------&lt;br /&gt;# Author: Elliot Winkler &lt;elliot.winkler@gmail.com&gt;&lt;br /&gt;# Created: 11 Mar 2008&lt;br /&gt;#==========================================================================================&lt;br /&gt;&lt;br /&gt;my $dir = $ARGV[0] || ".";&lt;br /&gt;my $cmd = "find $dir";&lt;br /&gt;my @listing = sort grep { $_ } split /\n/, `$cmd`;&lt;br /&gt;&lt;br /&gt;my %exts;&lt;br /&gt;for (@listing) {&lt;br /&gt;  my($ext) = /\.([a-z]+)$/;&lt;br /&gt;  next unless $ext;&lt;br /&gt;  $exts{lc $ext}++;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;for (sort keys %exts) {&lt;br /&gt;  print uc($_).": ".$exts{$_}."\n";&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Example:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;$ cd ~/docs&lt;br /&gt;$ howmany&lt;br /&gt;CSV: 3&lt;br /&gt;DOC: 1&lt;br /&gt;KEY: 1&lt;br /&gt;PUB: 1&lt;br /&gt;SQL: 1&lt;br /&gt;TEXT: 1&lt;br /&gt;TXT: 9&lt;br /&gt;XCF: 2&lt;br /&gt;XLS: 1&lt;br /&gt;ZIP: 1&lt;br /&gt;$ howmany ~/docs&lt;br /&gt;CSV: 3&lt;br /&gt;DOC: 1&lt;br /&gt;KEY: 1&lt;br /&gt;PUB: 1&lt;br /&gt;SQL: 1&lt;br /&gt;TEXT: 1&lt;br /&gt;TXT: 9&lt;br /&gt;XCF: 2&lt;br /&gt;XLS: 1&lt;br /&gt;ZIP: 1&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Note:&lt;/b&gt; This only works on Linux/Unix, because it relies on a Linux/Unix-only command to pull up the list of files. A future update may include support for Windows, though it would be pretty easy to find out how to fix it.</description>
      <pubDate>Tue, 11 Mar 2008 14:57:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5211</guid>
      <author>mcmire ()</author>
    </item>
    <item>
      <title>vortx.pl</title>
      <link>http://snippets.dzone.com/posts/show/5073</link>
      <description>#!/usr/bin/perl -w&lt;br /&gt;# Vortex0.pl&lt;br /&gt;#----------------&lt;br /&gt;&lt;br /&gt;use strict;&lt;br /&gt;use Socket;&lt;br /&gt;&lt;br /&gt;# initialize host and port&lt;br /&gt;my $host = shift || 'localhost';&lt;br /&gt;my $port = shift || 5842;&lt;br /&gt;my $server = "vortex.labs.pulltheplug.org";&lt;br /&gt;&lt;br /&gt;# create the socket, connect to the port&lt;br /&gt;socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])&lt;br /&gt;   or die "Can't create a socket $!\n";&lt;br /&gt;connect( SOCKET, pack( 'Sn4x8', AF_INET, $port, $server ))&lt;br /&gt;       or die "Can't connect to port $port! \n";&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;my $comm;&lt;br /&gt;while($comm=&lt;STDIN&gt;)&lt;br /&gt;{&lt;br /&gt;    chomp $comm;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    if($comm ne '')&lt;br /&gt;    {&lt;br /&gt;	&lt;br /&gt;	print "\n Received 4-Byte Password '", $pass,"'\n";&lt;br /&gt;	$SOCKET-&gt;recv($pass,4);&lt;br /&gt;&lt;br /&gt;        print "\n Sending message '",$pass,"'";&lt;br /&gt;        if($SOCKET-&gt;send($pass))&lt;br /&gt;        {&lt;br /&gt;            print "[Done] CONGRATS! Time for some Vodka","\n";&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    else&lt;br /&gt;    {&lt;br /&gt;        # Send an empty message to server and exit&lt;br /&gt;        $SOCKET-&gt;send($pass);&lt;br /&gt;        exit 1;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;close SOCKET or die "close: $!";</description>
      <pubDate>Fri, 01 Feb 2008 16:11:43 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5073</guid>
      <author>netfish (netfish)</author>
    </item>
    <item>
      <title>Interactive Text-to-Speech (Windows, Perl)</title>
      <link>http://snippets.dzone.com/posts/show/5047</link>
      <description>This script calls the Windows OLE for the built in TTS. Type what you want the computer to say at the prompt and hit enter. To quit type ":q" (minus the quotation marks).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;use Win32::OLE qw( EVENTS );&lt;br /&gt;&lt;br /&gt;get_text();&lt;br /&gt;&lt;br /&gt;sub get_text{&lt;br /&gt;	$output_speech = &lt;STDIN&gt;;&lt;br /&gt;	chomp($output_speech);&lt;br /&gt;	if($output_speech ne ":q"){&lt;br /&gt;		say_this();&lt;br /&gt;		get_text();&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;sub say_this{&lt;br /&gt;	my $myTTS = new Win32::OLE( "Sapi.SpVoice" ); &lt;br /&gt;	$myTTS-&gt;Speak( "$output_speech" );&lt;br /&gt;	while( $myTTS-&gt;{Speaking} )&lt;br /&gt;	{&lt;br /&gt;		Win32::OLE-&gt;SpinMessageLoop();&lt;br /&gt;		Win32::Sleep( 100 );&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 28 Jan 2008 19:59:29 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5047</guid>
      <author>minitotoro (Natalie)</author>
    </item>
    <item>
      <title>find and replace text from the shell</title>
      <link>http://snippets.dzone.com/posts/show/4645</link>
      <description>Snagged from http://snippets.dzone.com/posts/show/116&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;find . -name '*.txt' -print0 |xargs -0 perl -pi -e 's/find/replace/g'&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 12 Oct 2007 19:02:38 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4645</guid>
      <author>sikelianos (Zeke Sikelianos)</author>
    </item>
    <item>
      <title>Browser automation using perl LWP</title>
      <link>http://snippets.dzone.com/posts/show/4587</link>
      <description>// This is a sample code used to measure reports response times on a OAS application.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/perl&lt;br /&gt;#&lt;br /&gt;# LWP connection to the Datamart Portal&lt;br /&gt;# Timing of the main reports&lt;br /&gt;#&lt;br /&gt;&lt;br /&gt;use strict;&lt;br /&gt;require LWP::UserAgent;&lt;br /&gt;&lt;br /&gt;my $ua = LWP::UserAgent-&gt;new;&lt;br /&gt;&lt;br /&gt;sub isodate() {&lt;br /&gt;        my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];&lt;br /&gt;        $mon++; # 0-based index&lt;br /&gt;        $year = $year + 1900;&lt;br /&gt;        my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);&lt;br /&gt;        return $date;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;sub datamart_login {&lt;br /&gt;        my ( $user, $pass ) = @_;&lt;br /&gt;        my $time_begin=time();&lt;br /&gt;        my $url='http://daprd:7782/portal/page?_pageid=37,134413,37_134422&amp;_dad=portal&amp;_schema=PORTAL';&lt;br /&gt;        my $req = HTTP::Request-&gt;new( GET =&gt; $url );&lt;br /&gt;        my $resp = $ua-&gt;request($req);&lt;br /&gt;        my $loginform = $resp-&gt;content ;&lt;br /&gt;        if ( $loginform !~ /Entrez votre nom utilisateur/ ) {&lt;br /&gt;                die isodate()." Failed to get the logon page of the Web Site\n";&lt;br /&gt;        } else {&lt;br /&gt;                my $locale="";&lt;br /&gt;                my ($v) = $loginform =~ /NAME=\"v\" value=\"(.+)\"/;&lt;br /&gt;                my ($site2pstoretoken) = $loginform =~ /NAME=\"site2pstoretoken\" value=\"(.+)\"/;&lt;br /&gt;                my ($submiturl) = $loginform =~ /form method=\"POST\" action=\"(.*?)\"/;&lt;br /&gt;                $resp = $ua-&gt;post( $submiturl,&lt;br /&gt;                   [&lt;br /&gt;                     ssousername =&gt; $user,&lt;br /&gt;                     password =&gt; $pass,&lt;br /&gt;                     v =&gt; $v,&lt;br /&gt;                     locale =&gt; $locale,&lt;br /&gt;                     site2pstoretoken =&gt; $site2pstoretoken&lt;br /&gt;                   ],&lt;br /&gt;                );&lt;br /&gt;                $resp = $ua-&gt;get($url);&lt;br /&gt;                $resp = $ua-&gt;get($url);&lt;br /&gt;                if ( $resp-&gt;content !~ /Crit..res de recherche/ ) {&lt;br /&gt;                        die isodate()." Failed to get the main page of Portal\n";&lt;br /&gt;                }&lt;br /&gt;        }&lt;br /&gt;        print join(";",isodate(),"Time to log on the Portal",time()-$time_begin,$url)."\n";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;sub datamart_testurl {&lt;br /&gt;        my ($label,$url,$expected)=@_;&lt;br /&gt;        my $time_begin=time();&lt;br /&gt;        my $resp;&lt;br /&gt;        $resp = $ua-&gt;get($url);&lt;br /&gt;        $resp = $ua-&gt;get($url) if $resp-&gt;content !~ /$expected/;        # We try two times !&lt;br /&gt;        if ( $resp-&gt;content !~ /$expected/ ) {&lt;br /&gt;                print STDERR isodate()." Test Failed on $label. $expected not found in response.\n";&lt;br /&gt;                print STDERR $resp-&gt;as_string;&lt;br /&gt;        } else {&lt;br /&gt;                print join(";",isodate(),$label,time()-$time_begin,$url)."\n";&lt;br /&gt;        }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;$ua-&gt;timeout(1200);&lt;br /&gt;$ua-&gt;cookie_jar({});&lt;br /&gt;$ua-&gt;agent( 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)' );&lt;br /&gt;#push @{ $ua-&gt;requests_redirectable }, 'POST';&lt;br /&gt;&lt;br /&gt;# &gt;&gt;&gt;&gt; Main code here&lt;br /&gt;&lt;br /&gt;datamart_login("xxxx","xxxx");&lt;br /&gt;&lt;br /&gt;open FH,"/exploit/scripts/appli/check_datamart.ini" or die "Unable to open check_datamart.ini";&lt;br /&gt;while (&lt;FH&gt;) {&lt;br /&gt;        chomp();&lt;br /&gt;        my ($report,$expected,$url) = split /;/;&lt;br /&gt;        datamart_testurl($report,$url,$expected);&lt;br /&gt;}&lt;br /&gt;close FH;&lt;br /&gt;&lt;br /&gt;# &lt;&lt;&lt;&lt; Main code here&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 28 Sep 2007 11:48:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4587</guid>
      <author>bouffon69 (Sylvain Le Courtois)</author>
    </item>
  </channel>
</rss>
