perl写的一个日志监控脚本,供大家学习参考。
#!/usr/bin/perl
#make by skylway 20121203
use warnings;
use strict;
use POSIX qw(strftime);
use Encode;
#日志文件相关变量
my $path="你的路径";
my $logday=strftime("%Y%m%d",localtime(time));
my $logfile="$path/filter_$logday_1.log";
my $mydate=strftime("%Y%m%d:%H%M%S",localtime(time));
my $myhour=strftime("%H",localtime(time));
#mon_sms_file.tag定义记录文件大小
my $tmpfile="/tmp/.127glsms/mail_v1.tmp";
my $maillog="/tmp/.127glsms/mail_v1.log";
my $mylogfile="/tmp/.127glsms/smslog_v1.log";
#my $mailcmd="/usr/bin/bsmtp";
my %smstotal;
my $seekpos;
my %filter;
#定义函数,获取文件大小
sub getlogsize(){
my $file=$logfile;
open(LOG,">/tmp/.127glsms/monsms114filesize.log")||die "ERROR:cann't open $!";
my $size= -s $file;
print LOG "$file $sizen";
close (LOG);
}
#定义函数,分析查看日志文件
sub viewlog(){
my $file=$logfile;
my $logsize;
if ( ! -d "/tmp/.127glsms/"){
mkdir "/tmp/.127glsms/";
}
if( $myhour < 1){
unlink "/tmp/.127glsms/monsms114filesize.log";
}
if (-f "/tmp/.127glsms/monsms114filesize.log"){
open(TAGF,"/tmp/.127glsms/monsms114filesize.log");
while(<TAGF>){
$seekpos=(split/s+/,$_)[1];
#print "$seekposn";
}
close(TAGF);
open(FFFF,$file)||die "ERROR:$!";
seek(FFFF,$seekpos,0);
while(<FFFF>){
chomp;
if(/A.*(86ddddddddddd)->.*CF:(.*)HIT_B:(.*)Rule.*MSG:(.*)Z/){
my $user=$1;
my $cf=$2;
my $ukey=$3;
my $msg=$4;
$filter{$ukey}++;
my $userstr="$user||$cf||$ukey||$msg";
$smstotal{$userstr}++;
#my $ustr="$user||$uwhere||$msg";
#my $uipstr="$uip||$ipwhere||$msg";
#my $userip="$uip||$user||$msg";
#if($status=~/成功/){
# $hashustr{$ustr}++;
# $hashuipstr{$uipstr}++;
#if($ipwhere !~/移动/){
# $hashuseripstr{$userip}++;
#}
#}
}
}
}
open(MLGF,">>$tmpfile")||die "ERROR:$!";
print MLGF "##--------- 127FILTER SMS114 LOG MONITOR --------------##nn";
foreach(sort {$filter{$b} <=> $filter{$a}} keys %filter){
if($filter{$_} > 10){
print MLGF "n数量:$filter{$_} || 过滤类型及名称: $_n";
}
}
foreach(sort {$smstotal{$b} <=> $smstotal{$a}} keys %smstotal){
if($smstotal{$_} > 5){
print MLGF "n数量:$smstotal{$_} || 过滤内容情况:$_n";
}
}
close(MLGF);
getlogsize();
}
sub sendmail(){
my $myweek=`date +%u`;
my $mailsize= -s "$tmpfile";
my $dataline = `cat $tmpfile |wc -l`;
my $hour = strftime("%H",localtime(time));
if(-f "$tmpfile" && $dataline >1 ){
if($myweek=~/1|2|3|4|5/ && $hour >= 1 && $hour < 18){
system("cat $tmpfile > $maillog");
system("cat $maillog |/usr/bin/bsmtp -f 发送邮箱 -s "主题" -h smtp.api.localdomain 你的邮箱");
}else{
system("cat $tmpfile > $maillog");
ssystem("cat $maillog |/usr/bin/bsmtp -f 发送邮箱 -s "主题" -h smtp.api.localdomain 你的邮箱");
}
}
unlink ("$tmpfile");
}
###mail scripts####
viewlog();
sendmail();