将多个grep组合到一个perl脚本中

将多个grep组合到一个perl脚本中,perl,grep,Perl,Grep,上面是一个Perl脚本的代码片段,它实际上搜索了一堆日志文件,进行了模式搜索,打印了一个摘要,并将其作为带有附件的邮件发送 希望优化3种模式的搜索,但不希望增加grep语句的数量,因为日志文件每天有10k,这将增加脚本的运行时间,现在脚本将在大约10分钟内完成 到目前为止,它搜索“Errno 110”,但希望添加“Errno 110”、“Errno 13”和“Errno 43”的组合,并相应地打印摘要,正如您在printf语句中看到的那样,“Errno 110”是硬编码的 sub logProc

上面是一个Perl脚本的代码片段,它实际上搜索了一堆日志文件,进行了模式搜索,打印了一个摘要,并将其作为带有附件的邮件发送

希望优化3种模式的搜索,但不希望增加grep语句的数量,因为日志文件每天有10k,这将增加脚本的运行时间,现在脚本将在大约10分钟内完成

到目前为止,它搜索“Errno 110”,但希望添加“Errno 110”、“Errno 13”和“Errno 43”的组合,并相应地打印摘要,正如您在printf语句中看到的那样,“Errno 110”是硬编码的

sub logProcessing {
    my $logpath = $File::Find::dir;
    my $logfile = $_;
    if ( $File::Find::name =~ m!$logDir/(.*?)/$pattern! and -d $File::Find::dir ) { $dirCount++ };
    if ( $File::Find::name =~ m!$logDir/(.*?)/$pattern! and -f $File::Find::name ) { $fileCount++ };
    if ( $File::Find::name =~ m!$logDir/(.*?)/$pattern! and -f $File::Find::name ) {
        my $errorsSeen = `grep 'Errno 110' $File::Find::name|uniq`;
        if ($errorsSeen ne "") {
            $errorCount++;
            my $hostname = $1;
            my $lastModTime = localtime ( (stat $File::Find::name)[9] );
            printf FILE "%3s %20s %50s %30s %50s\n", $hostname, 'Errno 110', $logpath, $logfile, $lastModTime;
        }
        else {
            $nullCount++
        }
    }
}
#/usr/bin/perl
#
#程序版本1-添加的错误过滤器
#并添加了错误类型
##加载模块
严格使用;
使用警告;
使用File::Find;
使用时间::件;
使用MIME::Lite;
使用File::Slurp;
使用Fcntl qw(:flock);
使用Getopt::Long qw(:config no_ignore_case);
##通用变量
我的$progversion=“1”;
我的$progrevision=“1”;
my$prog\u name=“error\u alert.pl”;
我的帮助;
我的$version;
我的$dryrun;
##主要程序变量
my$dc=‘IN’;
chomp($dc);
my$fileDate=localtime->ymd(“-”);
chomp($fileDate);
my$logDir=“/home/ajoy/alert dc/testlogs”;
my$Date=localtime->ymd(“”);
my$pattern=“applmgr\.log\.$Date”;
chomp($日期);
咀嚼(模式);
我的$fileCount=0;
我的$dirCount=0;
我的$errorCount=0;
我的$nullCount=0;
#我的$to='ajoy。bharath@XXXXXX';
我给你的美元123@xyz.com, 345@xyz.com, xyz@abc.com';
我的$from='否-reply@xyz.com';
my$subject=“日志警报($dc)”;
my$subDate=localtime->ymd(“/”);
chomp($subDate);
my$message=“日期:-$subDate的$dc日志处理状态
请查找统计信息的附加文件…”; my$outFile=“$logDir/applmgr\u status\u$dc-$fileDate.txt”; ##锁定此脚本的多个实例 打开我的$lockFile“>”、“$logDir/script.lock”或die$!; flock$lockFile,LOCK_EX | LOCK_NB或die“不允许多个实例:$!”; 打印$lockFile“$$”; ##选项子程序 子打印_用法(){ 打印“用法:$prog_name或$prog_name,带有选项[-v |--version][h |--help][d |--dryrun]\n”; 出口(1); } 子打印版本(){ 打印“$prog\u name:$progversion.$progrevision\n”; 出口(0); } 子打印\u帮助(){ 打印“$prog_name:$progversion.$progrevision”; 打印“\n”; 打印“用法:$prog_name或$prog_name,带选项[-v |--version][h |--help][d |--dryrun]”; 打印“\n”; 打印“$prog_name=流程日志和流程摘要并发送邮件\n”; 打印“-v |--version=版本。\n”; 打印“-h |--help=此屏幕。\n”; 打印“-d |--dryrun=进程日志和进程摘要并输出到stdout,而不是发送邮件\n\n”; 打印“\n”; 出口(0); } 亚干运行{ 打开(文件“>$logDir/applmgr_status_$dc-$fileDate.txt”)或死“无法打开文件”; printf文件“%3s%20s%30s%40s%50s\n”、“主机名”、“错误”、“日志路径”、“日志文件”、“修改时间”; 打印文件“%3s\n”,“-”x 150; 查找(\&logProcessing,$logDir); 打印文件“\n\n摘要\n”; printf文件“%3s\n”,“-”x20; 打印文件“为错误调查的主机数:$dirCount\n”; 打印文件“为错误调查的日志文件数:$fileCount\n”; 打印文件“处理错误的主机数:$errorCount\n”; 打印文件“无错误处理的主机数:$nullCount\n”; 关闭(文件); my$data=读取文件($outFile); 打印$数据; 出口(0); } #主程序从这里开始 如果(!GetOptions(!v|version'=>\$version,'h|help'=>\$help,'d|dryrun'=>\$dryrun)),则打印使用情况(); 如果($help),则打印帮助(); 打印版本()如果($version); 干运行()如果($dryrun); 打开(文件“>$logDir/applmgr_status_$dc-$fileDate.txt”)或死“无法打开文件”; printf文件“%3s%20s%30s%40s%50s\n”、“主机名”、“错误”、“日志路径”、“日志文件”、“修改时间”; 打印文件“%3s\n”,“-”x 150; 查找(\&logProcessing,$logDir); 打印文件“\n\n摘要\n”; printf文件“%3s\n”,“-”x20; 打印文件“调查错误的播客主机数:$dirCount\n”; 打印文件“为错误调查的日志文件数:$fileCount\n”; 打印文件“捕获到错误的播客主机数:$errorCount\n”; 打印文件“无错误捕获的播客主机数:$nullCount\n”; &警报信息; ##主程序子程序 子日志处理{ my$logpath=$File::Find::dir; 我的$logfile=$\uux; 如果($File::Find::name=~m!$logDir/(.*)/$pattern!和-d$File::Find::dir){$dirCount++}; 如果($File::Find::name=~m!$logDir/(.*)/$pattern!和-f$File::Find::name){$fileCount++}; 如果($File::Find::name=~m!$logDir/(.*)/$pattern!和-f$File::Find::name){ my$errorsSeen=`grep'Errno 110'$File::Find::name | uniq`; 如果($errorsSeen“”){ $errorCount++; 我的$hostname=$1; my$lastModTime=localtime((stat$File::Find::name)[9]); printf文件“%3s%20s%50s%30s%50s\n”、$hostname、$Errno 110、$logpath、$logfile、$lastModTime; }else{$nullCount++} } } 关闭(文件); 子警报消息{ my$msg=MIME::Lite->new( From=>$From, To=>$To, 主题=>$Subject, 类型=>“多部分/混合” ); $msg->attach( 类型=>'text/html', 数据=>$message ); $msg->attach( 类型=>'text/html', 路径=>$outFile, 处置=>“附件” ); $msg->send; }
========================================================== 示例日志文件-applmgr.log.20170303

    #!/usr/bin/perl
#

# program revision 1 - addded error filter
# and added error types 
## Loading Modules

use strict;
use warnings;
use File::Find;
use Time::Piece;
use MIME::Lite;
use File::Slurp;
use Fcntl qw(:flock);
use Getopt::Long qw(:config no_ignore_case);

## Generic Variables

my $progversion = "1";
my $progrevision = "1";
my $prog_name = "error_alert.pl";
my $help;
my $version;
my $dryrun;

## Main Program Variables

my $dc = 'IN';
chomp($dc);
my $fileDate = localtime->ymd("-");
chomp($fileDate);
my $logDir = "/home/ajoy/alert-dc/testlogs";
my $Date = localtime->ymd("");
my $pattern = "applmgr\.log\.$Date";
chomp($Date);
chomp($pattern);
my $fileCount = 0;
my $dirCount = 0;
my $errorCount = 0;
my $nullCount = 0;

#my $to = 'ajoy.bharath@XXXXXX';
my $to = '123@xyz.com, 345@xyz.com, xyz@abc.com';
my $from = 'no-reply@xyz.com';
my $subject = "Log Alert ($dc)";
my $subDate = localtime->ymd("/");
chomp($subDate);
my $message = "<h2>Log Processing Status of $dc for Date:- $subDate </h2> <br> <h3>Please find the attached file for stats..!</h3>";
my $outFile = "$logDir/applmgr_status_$dc-$fileDate.txt";

## locking multiple instances of this script

open my $lockFile, ">", "$logDir/script.lock" or die $!; 
flock $lockFile, LOCK_EX|LOCK_NB or die "Multiple instance not allowed: $!";
print $lockFile "$$";

## Options Sub Routines

sub print_usage() {
    print "Usage: $prog_name or $prog_name with options [-v|--version] [-h|--help] [-d|--dryrun]\n";
    exit(1);
}

sub print_version() {
    print "$prog_name : $progversion.$progrevision\n";
    exit(0);
}

sub print_help () {
    print "$prog_name : $progversion.$progrevision";
    print "\n";
    print "Usage: $prog_name  or $prog_name with options [-v|--version] [-h|--help] [-d|--dryrun]";
    print "\n";
    print "$prog_name = process logs and process summary and send mail\n";
    print "-v|--version = Version.\n";
    print "-h|--help = This screen.\n";
    print "-d|--dryrun = process logs and process summary and output to stdout instead of sending mail\n\n";
    print "\n";
    exit(0);
}

sub dry_run {
   open(FILE, ">$logDir/applmgr_status_$dc-$fileDate.txt") or die "Cannot open file";
   printf FILE "%3s %20s %30s %40s %50s\n", "Host Name", "Errors", "Log Path", "Log FIle", "Modified Time";
   printf FILE "%3s\n", "-" x 150;
   find( \&logProcessing, $logDir);
   print FILE "\n\nSUMMARY\n";
   printf FILE "%3s\n", "-" x 20;
   print FILE "Number of Hosts investigated for error: $dirCount\n";
   print FILE "Number of LogFiles investigated for error: $fileCount\n";
   print FILE "Number of Hosts processed with errors: $errorCount\n";
   print FILE "Number of Hosts processed wihout errors: $nullCount\n";
   close(FILE);
   my $data = read_file($outFile);
   print $data;
   exit(0);
}

# Main Program starts here

print_usage() if ( ! GetOptions('v|version' => \$version, 'h|help' => \$help, 'd|dryrun' => \$dryrun));
print_help() if ($help);
print_version() if ($version);
dry_run() if ($dryrun);

open(FILE, ">$logDir/applmgr_status_$dc-$fileDate.txt") or die "Cannot open file";
printf FILE "%3s %20s %30s %40s %50s\n", "Host Name", "Errors", "Log Path", "Log FIle", "Modified Time";
printf FILE "%3s\n", "-" x 150;

find( \&logProcessing, $logDir);

print FILE "\n\nSUMMARY\n";
printf FILE "%3s\n", "-" x 20;
print FILE "Number of Podhosts investigated for error: $dirCount\n";
print FILE "Number of LogFiles investigated for error: $fileCount\n";
print FILE "Number of Podhosts harvested with errors: $errorCount\n";
print FILE "Number of Podhosts harvested wihout errors: $nullCount\n";

&alertMessage;

## Main Program Sub Routines

sub logProcessing {
    my $logpath = $File::Find::dir;
    my $logfile = $_;
    if ( $File::Find::name =~m!$logDir/(.*?)/$pattern! and -d $File::Find::dir ) { $dirCount++ };
    if ( $File::Find::name =~m!$logDir/(.*?)/$pattern! and -f $File::Find::name ) { $fileCount++ };
    if($File::Find::name =~m!$logDir/(.*?)/$pattern! and -f $File::Find::name) {
      my $errorsSeen = `grep 'Errno 110' $File::Find::name|uniq`;
      if ($errorsSeen ne "") {
      $errorCount++;
      my $hostname = $1;
        my $lastModTime = localtime ( (stat $File::Find::name)[9] );
        printf FILE "%3s %20s %50s %30s %50s\n", $hostname, 'Errno 110', $logpath, $logfile, $lastModTime;
        } else { $nullCount++ }
    }
}

close(FILE);

sub alertMessage {

  my $msg = MIME::Lite->new(
                 From     => $from,
                 To       => $to,
                 Subject  => $subject,
                 Type     => 'multipart/mixed'
                 );

  $msg->attach(
             Type  => 'text/html',
             Data  => $message
            );

  $msg->attach(
             Type         => 'text/html',
             Path         => $outFile,
             Disposition  => 'attachment'
   );

  $msg->send;
}
2017-03-03 08:35:13 UTC 965[14385]错误上载过程失败,原因是:错误(110,“连接超时”) 错误:[Errno 110]连接超时 2017-03-03 08:43:43 UTC 913[20057]错误上载过程失败,原因是:错误(110,“连接超时”) 错误:[Errno 110]连接超时 2017-05-26 08:10:14 UTC 278[7665]警告无法检查上载结果,出现异常 2017-03-03 08:35:13 UTC 965 [14385] ERROR upload process failed with: error(110, 'Connection timed out') error: [Errno 110] Connection timed out 2017-03-03 08:43:43 UTC 913 [20057] ERROR upload process failed with: error(110, 'Connection timed out') error: [Errno 110] Connection timed out 2017-05-26 08:10:14 UTC 278 [7665] WARNING Failed to check upload result with: Exception('Received error response 400 Bad Request from HTTP server',) 2017-05-26 08:10:14 UTC 288 [7665] ERROR upload process failed with: error(32, 'Broken pipe') error: [Errno 32] Broken pipe 2017-05-26 08:10:14 UTC 278 [7665] WARNING Failed to check upload result with: Exception('Received error response 400 Bad Request from HTTP server',) 2017-05-26 08:10:14 UTC 288 [7665] ERROR upload process failed with: error(32, 'Broken pipe') error: [Errno 32] Broken pipe 2017-05-26 08:10:14 UTC 278 [7665] WARNING Failed to check upload result with: Exception('Received error response 400 Bad Request from HTTP server',) 2017-05-26 08:10:14 UTC 288 [7665] ERROR upload process failed with: error(32, 'Broken pipe') error: [Errno 32] Broken pipe 2017-03-03 08:29:24 UTC 010 [9417] ERROR upload process failed with: error(110, 'Connection timed out') error: [Errno 110] Connection timed out