in reply to Passing epoch time to function to compare open session time and close session time
Here I have rejigged your code somewhat to compile under strict and warnings, however I have tried to leave it as original as possible so you find it familiar and easy to understand.
#!/usr/bin/perl use warnings; use strict; use Time::Local; my $x = getTime(); my $d1; my $d2; my $ID; my $epoch; my %openTime; my %account; my %totalSession; my %dSession; sub getTime { (my $sec,my $min,my $hour,my $mday,my $month,my $year,my $wday,my + $yday,my $isdst)=localtime(time); $epoch = timelocal($sec, $min, $hour, $mday, $month, $year); return $epoch; } my @fileTotal = `ls /u/user/myarea/test/file*`; #foreach loop opens each log file foreach my $file (@fileTotal) { chomp($file); open(FILEREAD, "< $file"); open FILEREAD, "< $file" or die "Can't open $file for reading - $ +?"; while (my $linebuf = <FILEREAD>) { chomp($linebuf); # remove <CR> at the end my @data = split(/[ ]+/, $linebuf); if( $data[6] eq "session" && $data[7] eq "opened") { $d1 = index($linebuf, "[", 0); $d2 = index($linebuf, "]", ($d1+1)); $ID = substr($linebuf, ($d1+1), ($d2-$d1-1)); $openTime{$ID} = $epoch; $account{$ID} = $data[10]; print "open time= $openTime{$ID}\n"; } elsif( $data[6] eq "session" && $data[7] eq "closed") { # user SSH logoff session $d1 = index($linebuf, "[", 0); $d2 = index($linebuf, "]", ($d1+1)); $ID = substr($linebuf, ($d1+1), ($d2-$d1-1)); my $closeTime = $epoch; print "closetime= $closeTime\n"; if( defined $account{$ID}) { my $userAccount = $account{$ID}; my $duration = $closeTime - $openTime{$ID}; #inter +val $totalSession{$userAccount}++; $dSession{$userAccount} += $duration; } } } close FILEREAD; } foreach $x (sort(keys %totalSession)) { my $averageSession = $dSession{$x}/$totalSession{$x}; printf "%-10s %10s %10s \t %.2f\n",$x,$totalSession{$x},$dSession +{$x}, $averageSession; }
I used this as an example fo input:
Jan 31 08:40:19 ubuntu01 sshd[32346]: pam_unix(sshd:session): session opened for user user1 by (uid=1)
Jan 31 08:45:19 ubuntu01 sshd[32346]: pam_unix(sshd:session): session closed for user user1 by (uid=1)
That I found in what I believe to be an alternate post of yours.
As you will be able to see from a simple output debug I put in, epoch is printed on both 'opened' and 'closed' and prints the same number, hence you're '0's issue. I would suggest rethinking your method of determing 'time' and the difference between a 'connection open' time and a 'connection closed' time.
By no means am I guaranteeing that this code is the best way to do it, it is simply my honest interpretation from your's to 'safe/compilable code' - My usual caveat applies - all edits and suggestions and errors found are more than welcomed as always.
All the best - your ever faithfull functioning perloHolic
|
|---|