DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Retrieve Cisco Router Traffic Statistics Using Perl And RRDTOOL And PHP

03.28.2008
| 8780 views |
  • submit to reddit
        Traffic retrieving perl script:
    #!/opt/csw/bin/perl -w
    ##################################################
    # rrdtraf.pl
    #
    # Trafego de equipamentos Cisco
    #
    # 2006.01.12 - Adriano P. 
    # $Id: $

    ######################
    require 5.003;
    use strict;
    use SNMP_Session;
    use BER;
    use SNMP_util "0.90";
    use Time::Local;
    use RRDs;
    use Getopt::Long;
    use Pod::Usage;

    ##### GLOBAL #####
    my %opt;
    my @routers;
    my $IP_APPEND="::2:2";
    my $ERROR;
    my %rrd;

    ##################################################################
    sub main {
    init();

    Options(%opt);

    open(PAR, "rrdtraf.par") || die "Problema ao abrir rrdtraf.parn";

    Msg("* Coletando dados dos switches");
    while () {
    next if grep(/^(#)/,$_);

    my ($community,$ip,$net,@if) = split /:/;
    #$ip = "${community}@${ip}"; #host:port:timeout:retries

    LeituraSNMP($community, $ip,@if);

    syswrite(STDOUT,'.',1) if (!$opt{verbose} && !$opt{V});
    }
    close(PAR);
    Msg("n","* Fim");
    }

    main;
    exit 0;

    ##################################################################
    sub CriaRRD($) {
    my $arquivo = shift;

    print "- Criando base de dados:($arquivo) - " if $opt{verbose};

    RRDs::create ("$arquivo", "--start", time(),
    "--step", "300",
    "DS:ifInOctets:COUNTER:600:0:U",
    "DS:ifOutOctets:COUNTER:600:0:U",
    "RRA:AVERAGE:0.5:1:600",    #2 dias, com amostra de 5min
    "RRA:AVERAGE:0.5:6:700",    #2 semanas, com amostra de 30min
    "RRA:AVERAGE:0.5:24:775",    #2 meses, com amostra de 2h
    "RRA:AVERAGE:0.5:288:400");    #1 ano, com amostra de 1 dia
    if ($ERROR = RRDs::error) {
    die "$0: unable to graph $arquivo: $ERRORn";
    }

    print "okn" if $opt{verbose};
    }

    ##################################################################
    sub LeituraSNMP($$$) {
    my $community = shift;
    my $ip = shift;
    my (@if) = @_;

    my ($idx, $arquivo);
    my $ifInBroadcastPkts = "1.3.6.1.2.1.2.2.1.12";
    my $ifOutBroadcastPkts = "1.3.6.1.2.1.2.2.1.18";
    my @oids = ('ifIndex','ifDescr','ifInOctets','ifOutOctets');

    my @stack = &SNMP("${community}@${ip}", @oids);
    #$ip =~ s/.*@//;

    print "--[ $ip ]-----------n" if $opt{verbose};

    foreach $idx (@stack) {
    my ($id,$nome) = SNMP_util::Check_OID('ifDescr');
    next if (!${$idx}{$id});
    # Ignora interfaces nao cadastradas
    if( !grep(/^${$idx}{$id}$/,@if) ) {
    next;
    }

    my @dados = ();
    $dados[0] = $ip;                # 1: ip
    @dados[1,2,3,4] = &Dados($idx,@oids);
    my $ifIndex = $dados[1];

    $arquivo = "${ip}_${ifIndex}.rrd";
    if (! -e "$arquivo") {
    CriaRRD($arquivo);
    }
    AtualizaRRD($arquivo, @dados);
    }
    }

    ##################################################################
    sub AtualizaRRD(@) {
    my $arquivo = shift;
    my (@dados) = @_;

    print "- $dados[0], $dados[1], $dados[2], $dados[3], $dados[4]n" if $opt{verbose};

    RRDs::update ($arquivo, "N:$dados[3]:$dados[4]");
    }

    ##################################################################
    sub GrafRRD {
    my ($start_date,$eqto) = @_;

    print "Gerando grafico ($start_date)...";

    my @option = ("-s", $start_date, "-w", "600", "-h", "170",
    "-e", "now", "--alt-autoscale", "-l 0",
    "-x", "HOUR:1:DAY:1:HOUR:2:0:%H");

    if ($start_date >= 2) {

    ######################
    # GRAPH 1
    RRDs::graph ("$eqto.gif", @option,
    "DEF:in=$eqto.gif:ifInOctets:AVERAGE",
    "DEF:out=$eqto.gif:ifOutOctets:AVERAGE",
    "LINE2:c13#0000aa:Entrada",
    "LINE2:c14#ff66ff:Saida");
    if ($ERROR = RRDs::error) {
    die "$0: unable to graph $eqto.gif: $ERRORn";
    }

    }

    print "okn";
    }

    ##################################################################
    sub SNMP($@) {
    my $ip = shift;
    my @oids = @_;

    my $ip_="$ip${IP_APPEND}";
    my ($idx,$oid,@stack);

    foreach my $tuple (snmpwalk($ip_, @oids)) {
    my($var,$counter) = split /:/, $tuple, 2;
    $idx = substr($var, rindex($var,'.')+1);
    $oid = substr($var, 0, length($var)-length($idx)-1);
    #warn "* $vart$countern" if $opt{V};
    $stack[$idx]{$oid} = $counter;
    }

    return @stack;
    }

    ##################################################################
    sub Dados($$) {
    my $var = shift;
    my @oids = @_;

    my @dados = ();

    for(my $i=0; $i  2) if $$opt{man};
    }

    ##################################################################
    sub init {
    # queue up reading the MIB file
    #&snmpQueue_MIB_File("/home/adr/mibs/IWFG.MIB");
    $SNMP_Session::suppress_warnings = 2;
    $SNMP_util::Debug = 0;
    $= = 1000;
    }

    #eof

rrdtraf.par - sample file
    community:10.1.2.3:Comment:FastEthernet0/1:FastEthernet0/2
    community:10.1.2.4:Comment:FastEthernet0/1
    community:10.1.2.5:Comment:FastEthernet0/1:FastEthernet0/2:FastEthernet0/12:FastEthernet0/18

PHP script to plot the traffic graph:
    {!--
    ##################################################
    # rrdgraph.php
    #
    # Plotagem dos graficos de arquivos rrd
    #
    # 2006.01.12 - Adriano P.
    # $Id: $
    --}
    {?php
    $display = $_GET['display'];

    if ($display == 'image') {

    header ("Content-type: image/png",false);

    $display = $_GET['display'];
    $rrdtool = "/opt/csw/bin/rrdtool ";
    $graph_opt =     "--height 150 --width 550 " .
    "--start -172800 ".
    "--imgformat PNG ".
    "--no-minor ".
    "-c BACK#ffffff ".
    "-c SHADEA#ffffff ".
    "-c SHADEB#ffffff ".
    "-c FRAME#ffffff ".
    "-v 'bits/seg' -L 8  ";

    $arq1="/home/aprado/proj/traf/".$_GET['arq1'];

    $graph =
    "DEF:in1=$arq1:ifInOctets:AVERAGE ".
    "DEF:out1=$arq1:ifOutOctets:AVERAGE ".
    "CDEF:in1_bps=in1,8,* ".   #NÃO ESQUECER DE MULTIPLICAR POR 8
    "CDEF:out1_bps=out1,8,* ".  #(1 byte = 8 bits)
    "HRULE:0#000000:'       ' ".
    "AREA:in1_bps#6699cc:'Saida' ".
    "LINE2:out1_bps#003399:'Entrada' ";

    # function for rrdtool execution
    function rrdtool_execute($rrdtool, $command) {
    return fpassthru(popen($rrdtool . $command, "r"));
    }

    $command = $graph_opt . $graph;
    return rrdtool_execute($rrdtool, " graph - $command");
    }
    ?}

    {HTML}
    {HEAD}
    {STYLE TYPE="text/css"}
    H1 {
    font-weight: bold;
    font-size: 18pt;
    line-height: 18pt;
    font-family: arial,helvetica;
    font-variant: normal;
    font-style: normal;
    }
    BODY {
    color: black;
    background-color: white;
    font-size: 11pt;
    line-height: 12pt;
    font-family: arial,helvetica;
    font-variant: normal;
    font-style: normal;
    }
    {/STYLE}
    {/HEAD}
    {BODY}

    {CENTER}
    {TABLE}
    {?php

    function graphit($arq1, $descr1) {
    print "{tr align='center'}{td}{font color='#003399'}{b}$descr1{/b}{/font}{br}n";
    print "{/td}{/tr}n";
    print "{tr}{td align='center'}{img xsrc='/traf/rrdgraph.php?display=image&arq1=$arq1' border='0'}";
    print "{hr width='100%' size='2'}{/td}{/tr}n";
    }

    graphit("10.1.2.3_2.rrd","10.1.2.3 - f0/1: Comentario");
    graphit("10.1.2.3_3.rrd","10.1.2.3 - f0/2: Comentario");

    ?}
    {/TABLE}
    {/CENTER}
    {/BODY}
    {/HTML}