0

[已解决] 提前为我的错误代码感到抱歉(我是 Perl 新手)。我需要编写一个脚本来搜索文件中的某一行文本(它必须包含单词“authentication failure”和形式为“user=username”的用户名)并查找包含相同用户名的行的可能迭代以及当天记录的“认证失败”。日期和月份是我正在分析的文本每行的前两个单词。因此,每一行类似于:

"Jun 24 bla bla bla authentication failure bla bla bla user=mickey_mouse"

无论如何,不​​管我的目标是什么,我确信问题在于我对 Perl 的经验不足。所以请看看我的代码并告诉我是否有问题。

这是我到目前为止写的代码

#!usr/bin/perl
if (!defined($ARGV[0]) or !defined($ARGV[1])) {
    die "\nMissing arguments.\n";
}
open(FILE,$ARGV[0]) or die "Cannot open log file";
open(FILE1,$ARGV[0]) or die "Cannot open log file";

foreach $line(<FILE>) {
    chomp;
    if($line=~/authentication failure/ and $line=~/ user=/) {
        $count = 0;
        @chops = split("=", $line);
        $currentUser = $chops[-1];
        chomp($currentUser);
        @chops1 = split(" ", $line);
        $currentDate = $chops1[0]." ".$chops1[1];
        chomp($currentDate);
        print "\nUSER: $currentUser DATE: $currentDate\n";
        foreach $line1(<FILE1>) {
            chomp;
            if(index($line1, $currentUser) != -1 and 
               index($line1, $currentDate) != -1 and 
               $line1 =~ /authentication failure/) {
                $count++;
                print $count;
                if(count>=2) {
                    push($currentUser,@authenticFails);
                    last;
                }   
            }
        }
    }

}

print @authenticFails;

close(FILE);
close(FILE1);

[已解决] 感谢 sputnick 的回答和建议。无论如何,我弄清楚我的问题是什么。我只需要在嵌套的 -for- 块内(而不是在两个 fors 之前)编写第二个 open(ARGV[0]) 东西并在退出之前将其关闭。对于我正在使用第一个 -for- 块分析的每个当前行,这是重新开始对文件的每一行进行迭代的唯一方法。

再次感谢各位。

4

1 回答 1

3

我会使用菱形运算符 <>和哈希来计算出现次数:

use Modern::Perl; # enable strictures and features like "say"

my %hash;
# looping line by lines over the files
while (my $line = <ARGV>) {
    if ($line =~ /^(\w+\s+\d+)\s+.*?authentication\s+failure.*?user=(.*)/) {
        $hash{"$2|$1"}++;
    }
}
foreach my $key (keys %hash) {
    my ($user, $day) = split /\|/, $key;
    say "$hash{$key} auth failures for $user on $day";
}

输出

3 auth failures for mickey_mouse on  Jun 24
1 auth failures for mickey_mouse on  Jun 23
1 auth failures for xxx on  Jun 21

笔记

  • 总是把use strict; use warnings;use Modern::Perl
  • 如果您打开文件,请以正确的方式进行操作:open my $fh, "<", "file" or die $!您甚至可以or die通过添加use autodie像 Dadid W 建议的那样省略 。
于 2013-10-20T14:22:50.723 回答