是perl语法的新手,尝试设置一个计数器,从日志文件中计算密码失败的次数,然后将总数打印到控制台。我在屏幕上打印了很多数字,而不是最后只有一个总数。任何想法或指示都将有所帮助。
#!/usr/bin/perl
$count = 0;
open (MYFILE, 'auth.log');
while (my $line = <MYFILE>){
if ($line =~ /Failed password/){
$count++;
}
print $count;
#print "$linen" 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);
您需要将print $count
移出while
循环。
您还应该检查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