创建日志文件计数器

问题描述:

对于perl的语法来说,尝试设置一个计数器来记录从日志文件中发生失败的密码的时间,并将总数打印出到控制台。我在屏幕上打印了很多数字,而不是最后一个数字。任何想法或指示都会有所帮助。创建日志文件计数器

#!/usr/bin/perl 
$count = 0; 

open (MYFILE, 'auth.log'); 
while (my $line = <MYFILE>){ 
if ($line =~ /Failed password/){ 
$count++; 
} 
print $count; 
#print "$line\n" if $line =~ /Failed password/; 
#this was a print test to see if it would only print the failed password strings in the file.  
} 
close (MYFILE); 
+0

就移到高于'$打印算你撑;'。您在整个日志读数中打印计数。缩进帮助! – squiguy 2013-03-15 03:56:18

你需要移动print $countwhile循环。

您还应该检查我们的open的返回代码,否则您将不知道文件是否丢失或无法打开。

#!/usr/bin/perl 

use warnings; 
use strict; 

my $count = 0; 

open (my $fh, '<', 'auth.log') or die $!; 
while (my $line = <$fh>){ 
    if ($line =~ /Failed password/){ 
     $count++; 
    } 
} 
close $fh; 
print $count; 

最后,还有一种方法在命令行做到这一点:

grep -c 'Failed password' auth.log 
+1

使用三个参数打开:)。 – squiguy 2013-03-15 04:00:39

+0

完成,和词法文件句柄。 – 2013-03-15 04:02:02

+0

我还没有看到使用警告和严格使用,或者$ !,这是更高级的perl语法吗?我想更多地了解他们的工作?我很感兴趣。 :) – tattoo3d 2013-03-15 18:49:04