Mini Shell
#!/usr/bin/perl
#
# Made by Brandon Florin
use Getopt::Std; # needed to take options from the command line
$opt_h = undef;
$opt_i = undef;
$opt_o = undef;
$usage = "usage: $0 [-i <infile>] [-o <outfile>]\n" .
"\n".
"Where:\n".
" <infile> - Name of the mysql-generalquery.log file\n".
" <outfile> - Name of the outfile (results.txt)\n".
"\n";
getopts ('i:o:h');
if ( (defined($opt_h)) ) {
# print help
print $usage;
exit;
}
if ( (defined($opt_i)) ) {
# infile
$in = $opt_i;
} else {
# not defined, print usage
print $usage;
exit;
}
if ( (defined($opt_o)) ) {
# outfile
$out = $opt_o;
} else {
# not defined, print usage
print $usage;
exit;
}
open(IN,"<$in");
open(OUT,">$out");
undef($/);
$in = <IN>;
$in =~ s/^.*?\n//;
$in =~ s/^.*?\n//;
$in =~ s/^.*?\n//;
# Remove dates from the log
$in =~ s/\d{6}\s+\d+:\d{2}:\d{2}/\t/;
$/ = "\n";
close(IN);
# Parses the log into id/action/query
while ($in =~ /\t+\s+(\d+)\s+(.*?)\s{2}(.*?)(?=\n\s*\t{2}\s+\d+)/sg) {
($id, $action, $query) = ($1, $2, $3);
# If the action is quit, has no info, skip
next if ($action =~ /Quit/);
# If this action is Init ID, grab the username and insert into %ids hash
if ($action =~ /Init DB/) {
next if ($query =~ /Access denied/);
($username) = $query;
$username =~ s/^\s+//g;
$username =~ s/\s+$//g;
$ids{$id} = $username;
}
# If this action is Query, count number of queries per thread in %mysql hash
if ($action =~ /Query/) {
$query =~ s/^\s+//g;
$query =~ s/\s+$//g;
$query =~ s/\n+/\s/ig;
$query =~ s/\s\s+/ /g;
next if ($query !~ /./);
$mysql{$id} += 1;
}
}
# Adds up the total number of queries per user, not just per thread
foreach $id (keys %ids) {
$user = $ids{$id};
$user =~ s/^(.*?)_.*?$/$1/;
$new{$user} += $mysql{$id};
}
# Sort the results
@regexarray = map { { ($_ => $new{$_}) } }
sort { $new{$b} <=> $new{$a} } keys %new;
# Print out the results
foreach (@regexarray) {
($key, $value) = each %$_;
print OUT "$key :: $value\n";
}
close(OUT);
Zerion Mini Shell 1.0