2013-03-15 57 views
0

對於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

回答

4

你需要移動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