Главная страница


ru.cgi.perl

 
 - RU.CGI.PERL ------------------------------------------------------------------
 From : Al Zaharov                           2:5005/58.88   28 Jul 2001  14:19:36
 To : All
 Subject : посмотрите, плз, скрипт (рабочий), что с ним не так?
 -------------------------------------------------------------------------------- 
 
 нормально, а идеологические ака религиозные.. может, местами можно сделать 
 лучше? и не смотрите, что не дописан он до конца, может, что посоветуете, 
 тогда допишу\перепишу.. и, кстати, от того форка можно как-нибудь 
 избавиться? как ни пытался - не вышло.. и еще: а не лучше ли будет сделать 
 вывод мультипартом и у кого это получалось? метод, описанный в perldoc CGI 
 не получилось завести..
 
 #!/usr/bin/perl -w
 
 require 5.004;
 use locale;
 use POSIX qw (locale_h);
 use CGI qw (:standard);
 use strict;
 
 &main;
 
 sub main {
 $main::fetchipac = "/usr/local/sbin/fetchipac";
 $main::fetchipac_options = "";
 $main::ipacsum = "/usr/local/sbin/ipacsum";
 $main::title = "Traffic statistics";
 $main::form_head = "<H1> Show traffic statistics </H1>";
 $main::submit_btn = "Show me!";
 $main::sel = "Select period: ";
 $main::ssl_is_a_must = "0";
 $main::filter_to_ssl_user = "0";
 $main::check_referer = "0";
 @main::allow_referers = ('');
 my $charset = "koi8-r";
 
 ######  There are no user adjustable parameters below this line #############
 #############################################################################
 
 my $now = time();
 $main::me = $0;
 $main::me =~ s|^.*/([^/]+)$|$1|;
 # calculate time zone offset in seconds - use difference of output of date
 # command and time function, round it
 $main::tzoffset = 0;      # ! makeunixtime needs this!
 $main::tzoffset = int( ($now-makeunixtime(`date +"%Y%m%d%H%M%S"`)) / 60) *60;
 # get time zone name
 my $tzname = `date +%Z`; chop $tzname;
 my $starttime = 0 + $main::tzoffset;
 my $endtime = $now;
 
 my $timestamps = "";
 my $q = new CGI;
 $main::machine_name = "";
 my $options = "0";
 my $show_graph = "0";
 $main::skip_empty_lines = 0;
 $main::skip_empty_times = 0;
 $main::st_align = "center";
 $main::rulenames = "";
 $main::rulenumber = 0;
 
 setlocale(LC_CTYPE, "");
 
 if ($q->param('showpic')) {
   &print_pic($q->param('showpic'), $q->param('frame'));
 }
 
 print  $q->header(-type=>"text/html; charset=$charset"),
   $q->start_html($main::title);
 
 $options = print_get_form();
 if ($options eq "0") {
   print $q->end_html;
   exit;
 }
 
 ($starttime, $endtime) = split(/ /, set_time_frame($options), 2);
 if ($options =~ /graph/i) {
   $show_graph = "1";
   $main::st_align = "left";
 }
 if ($options =~ /showempty/i) {
   $main::skip_empty_lines = 1;
 }
 if ($options =~ /skiptimestamps/i) {
   $main::skip_empty_times = 1;
 }
 
 print "<TABLE align=$main::st_align CELLPADDING=4 CELLSPACING=2 BORDER=1>";
 
 open(DATA, "$main::fetchipac $main::fetchipac_options ".
           "-t$starttime,$endtime -m|") 
   || die "can't run $main::fetchipac\n";
 
 my $count=<DATA>;
 while(<DATA>)
 {
   if (/^(.)\s(\d+)$/) {
    my $ts = $2;
    if ($1 eq "*") {
       push(@main::timestamps, $ts);
    }
   }   
 }
 close DATA;
 
 pipe(PREAD,PWRITE);
 my $pid = fork();
 die "$main::me: can't fork: $!\n" if (!defined($pid));
 if ($pid == 0) {
   close PREAD;
   close STDOUT;
   open(STDOUT, ">&PWRITE") 
    || die "$main::me: cant redirect stdout to pipe\n";
   open(FETCHIPAC, "|$main::fetchipac -r -m") 
    || die "$main::me: can't exec $main::fetchipac\n";
         print(FETCHIPAC $main::timestamps[0],"-",$main::timestamps[-1],"\n");
   close(FETCHIPAC);
   close(PWRITE);
   exit;
 }
 close PWRITE;
 
 while(<PREAD>)
 {
   /^ADD\s*$/i or die "$main::me: bad line from fetchipac: $_\n";
   # second line of fetchipac output: timestamp no_of_records
   $_ = <PREAD> || last;
   /^(\d+)\s(\d+)$/ or die "$main::me: bad line from fetchipac: $_\n";
   my $timestamp = $1;
   # read each record
   &read_data_record("PREAD", $timestamp);
   
 }
 close PREAD;
 wait;
 
 print "</TABLE>\n\n";
 
 if ($show_graph eq "1") {
   my @rules_sorted = sort {$main::rulenames{$a}<=>$main::rulenames{$b}}
            keys %main::rulenames;
   print "<TABLE align=right>";
   my $iam = $q->url();
   my $fr = $q->param('list');
   foreach(@rules_sorted) {
    s/ /_/g;
        print "<TR><TD><IMG src=$iam?showpic=$_&frame=$fr>
           </TD></TR>";
   }
   print "</TABLE>\n\n";
 }
 print $q->end_html;
 } ######################### end of main proc #############################
 
 sub read_data_record {
   my($file, $irec);
   my($pkts, $bytes, $rule);
   my(@result);
 
   $file=shift;
   my $ttt=localtime(shift);
   my $header_printed = 0;
   $_ = <$file>;
   chop;
   /^\(\s*(.*)$/ or die "$main::me: bad line from fetchipac
           (expecting machine name): $_\n";
   $main::machine_name = $1;   # remember final machine name
   while(<$file>) {
    last if (/^\)$/);  # terminating line ')'
    /^(\d+)\s(\d+)\s\|(.*)\|$/
       or die "$main::me: bad line from fetchipac 
               (expecting rule item): $_\n";
    $bytes = $1;
    $pkts = $2;
    $rule = $3;
    if (!defined($main::rulenames{$rule})) {
       $main::rulenames{$rule}=$main::rulenumber++;
    }
    if (!$main::skip_empty_times && !$header_printed) {
       $header_printed = 1;
       print "<TR><TD><STRONG> $ttt </STRONG></TD>
        <TD> packets </TD>
        <TD> bytes </TD></TR>";
    }
    if (($main::skip_empty_lines && ($bytes ne "0"))
        || !$main::skip_empty_lines) {
       if (!$header_printed) { #print date, etc
        $header_printed = 1;
        print "<TR><TD><STRONG> $ttt </STRONG></TD>
           <TD> packets </TD>
           <TD> bytes </TD></TR>";
       }
       print "<TR><TD> $rule </TD><TD> $pkts </TD><TD> 
               $bytes </TD></TR>";
    }
   }
   # read another emtpy line (data format consistency)
   $_ = <$file>;
   die "$main::me: bad data from fetchipac (expected emtpy line): $_\n"
    if ($_ !~ /^$/);
 }
 
 sub set_time_frame {
   my($opt_t) = shift;
   my $starttime="";
   my $endtime="";
   my $i="";
   my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
   my @mofg = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 
   if ($opt_t =~ /^this\s*hour/i) {
    $opt_t = "the hour 0 hours ago";
   } elsif ($opt_t =~ /^last\s*hour/i) {
    $opt_t = "the hour 1 hour ago";
   } elsif ($opt_t =~ /^today/i) {
    $opt_t = "the day 0 days ago";
   } elsif ($opt_t =~ /^yesterday/i) {
    $opt_t = "the day 1 day ago";
   } elsif ($opt_t =~ /^the\s*day\s*before\s*yesterday/i) {
    $opt_t = "the day 2 days ago";
   } elsif ($opt_t =~ /^this\s*week/i) {
    $opt_t = "the week 0 weeks ago";
   } elsif ($opt_t =~ /^last\s*week/i) {
    $opt_t = "the week 1 week ago";
   } elsif ($opt_t =~ /^the\s*week\s*before\s*last\s*week/i) {
    $opt_t = "the week 2 weeks ago";
   } elsif ($opt_t =~ /^this\s*month/i) {
    $opt_t = "the month 0 months ago";
   } elsif ($opt_t =~ /^last\s*month/i) {
    $opt_t = "the month 1 month ago";
   } elsif ($opt_t =~ /^this\s*year/i) {
    $opt_t = "the year 0 years ago";
   } elsif ($opt_t =~ /^last\s*year/i) {
    $opt_t = "the year 1 year ago";
   } if ($opt_t =~ /^the\s*hour\s*(\d+)\s*hours?\s*ago/i) {
    $i=$1;
    my($thishour)=makeunixtime(sprintf("%04d%02d%02d%02d0000", 
       1900+$year, $mon+1, $mday, $hour));
    $starttime=$thishour - 60*60 * $i;
    $endtime = $thishour - 60*60 * ($i-1);
   } elsif ($opt_t =~ /^the\s*day\s*(\d+)\s*days?\s*ago/i) {
    $i=$1;
    my($thismorning)=makeunixtime(sprintf("%04d%02d%02d000000", 
       1900+$year, $mon+1, $mday));
    $starttime=$thismorning - 60*60*24 * $i;
    $endtime=$thismorning - 60*60*24 * ($i-1);
   } elsif ($opt_t =~ /^the\s*week\s*(\d+)\s*weeks?\s*ago/i) {
    $i=$1;
    $mday = $mday-($wday >0 ? $wday-1 : 6);
    if ($mday < 1) {
       $mon--;
       if ($mon < 0) {
        $mon += 12;
        $year--;
       }
       $mday += $mofg[$mon];
    }
    my($monday)=makeunixtime(sprintf("%04d%02d%02d000000", 
       1900+$year, $mon+1, $mday));
    $starttime=$monday - 60*60*24*7 * $i;
    $endtime=$monday- 60*60*24*7 * ($i-1);
   } elsif ($opt_t =~ /^the\s*month\s*(\d+)\s*months?\s*ago/i) {
    $mon = $mon - $1;
    while ($mon < 0) {
       $year--;
       $mon += 12;
    }
 
    $starttime=makeunixtime(sprintf("%04d%02d01000000", 
       1900+$year, $mon+1));
    $endtime=$starttime + 60*60*24*$mofg[$mon];
    $endtime += 60*60*24 if ((1900+$year)%4 ==0 && $mon==1);
   } elsif ($opt_t =~ /^the\s*year\s*(\d+)\s*years?\s*ago/i) {
    $i=$1;
 
    $starttime=makeunixtime(sprintf("%04d0101000000", 
       1900+$year-$i));
    $endtime=makeunixtime(sprintf("%04d0101000000", 
       1900+$year-$i+1));
   } elsif ($opt_t =~ /^ever/i) {
    $starttime=0;
    $endtime=time();
   } else {
    die "$main::me: Unknown time frame: \"$opt_t\"\n";
   }
   return sprintf "%s %s", $starttime, $endtime;
 }
 
 sub makeunixtime {
   my($y, $m, $d, $h, $i, $e);
   my $s = shift;
   my @moff = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 );
 
   $h=0; $i=0; $e=0;
   if ($s =~ /^(\d\d\d\d)(\d\d)(\d\d)/) {
    ($y, $m, $d) = ($1, $2, $3);
    if ($s =~ /^\d\d\d\d\d\d\d\d-?(\d\d)/) {
       $h=$1;
       if ($s =~ /^\d\d\d\d\d\d\d\d-?\d\d(\d\d)/) {
        $i=$1;
        if($s =~ /^\d\d\d\d\d\d\d\d-?\d\d\d\d(\d\d)/){
           $e=$1;
        }
       }
    }
   } else {
    return 0;
   }
   $y-=1970;
   $s = (($y)*365) + int(($y+2)/4);
   $s+=$moff[$m-1];
   $s+=$d-1;
   $s-- if (($y+2)%4 == 0 && $m < 3);
   $s*86400 + $h*3600 + $i*60 + $e + $main::tzoffset;
 }
 
 sub print_pic {
   my $pic=shift;
   my $frame=shift;
   $pic=~s/\_/ /g;
   if (defined($pic) && ($ENV{'HTTP_REFERER'} eq url())) {
    open (DATA, "$main::ipacsum -f\"$pic\" ".
           "-t\"$frame\" --png --png-asis --png-to-stdout|")
        || die "$main::me: can't run $main::ipacsum\n";
    binmode DATA;
    binmode STDOUT;
    print <DATA>;
    close DATA;
   } else {
    print header, start_html('Error'),
        h1({-align=>"center"}, 'This script is not intended for',
        'such a use. Sorry for any inconveniecies.'), end_html;
   }
   exit;
 }  
 
 sub print_get_form {
         my $q = new CGI;
   my %labels = ('today'=>'today', 'yesterday'=>'yesterday', 
       'thishour'=>'this hour', 'lasthour'=>'last hour', 
       'thisweek'=>'this week', 'lastweek'=>'last week', 
       'thismonth'=>'this month', 'lastmonth'=>'last month', 
       'thisyear'=>'this year', 'lastyear'=>'last year');
         my %opt_labels = ('graph'=>' build graphs', 
       'showempty'=>' skip lines with 0s only',
       'skiptimestamps'=>' skip timestamp with no data');
   print $q->startform,
       $main::form_head,
       "<P><TABLE CELLPADDING=4 CELLSPACING=2 BORDER=0>",
       "<TR><TD>$main::sel</TD><TD>",
       $q->popup_menu('list', 
    ['today','yesterday','thishour','lasthour',
    'thisweek','lastweek','thismonth','lastmonth',
    'thisyear','lastyear'],
    'today',\%labels), "</TD><TD>",
       $q->checkbox_group('options',
    ['graph','showempty','skiptimestamps'],
    ['showempty','skiptimestamps'],
    'true', \%opt_labels), "</TD>", 
 #      "<TD>Rules regexp: ", $q->textfield('regex','', 30, 50), "</TD>",
    "</TR></TABLE><P>",
       $q->submit(-value=>$main::submit_btn),
       $q->endform;
   if ($q->param) {
    return sprintf("%s %s", $q->param('list'), 
               join(" ", $q->param('options')));
   }
 }
 -- 
 
  wbw, kaiser
 --- tin/1.4.4-20000803 ("Vet for the Insane") (UNIX) (Linux/2.4.6 (i686))
  * Origin: e-will (2:5005/58.88)
 
 

Вернуться к списку тем, сортированных по: возрастание даты  уменьшение даты  тема  автор 

 Тема:    Автор:    Дата:  
 посмотрите, плз, скрипт (рабочий), что с ним не так?   Al Zaharov   28 Jul 2001 14:19:36 
 Re: посмотрите, плз, скрипт (рабочий), что с ним не так?   Pavel Ammosov   30 Jul 2001 14:43:29 
 Re: посмотрите, плз, скрипт (рабочий), что с ним не так?   Al Zaharov   01 Aug 2001 00:15:12 
 Re: посмотрите, плз, скрипт (рабочий), что с ним не так?   Pavel Ammosov   02 Aug 2001 15:25:58 
 Re: посмотрите, плз, скрипт (рабочий), что с ним не так?   Al Zaharov   05 Aug 2001 19:16:28 
 посмотpите, плз, скpипт (pабочий), что с ним не так?   Konstantin Petrenko   14 Aug 2001 12:38:38 
 Re: посмотрите, плз, скрипт (рабочий), что с ним не так?   Pavel Ammosov   14 Aug 2001 17:55:11 
 Re: посмотрите, плз, скрипт (рабочий), что с ним не так?   Al Zaharov   16 Aug 2001 09:18:06 
Архивное /ru.cgi.perl/2489529cb36a6.html, оценка 3 из 5, голосов 10
Яндекс.Метрика
Valid HTML 4.01 Transitional