2012-02-15 126 views
3

我如何知道已經用root帳戶登錄了多少次?Python閱讀文件

這裏是我使用至今在Python代碼:

myFile = open('file','r') 
count_rr = 0 
for line in myFile.readlines(): 
    list_of_line = line.split(' ') 
    if 'root' in list_of_line[?] 
      print 'root' 
      count_rr = counter_rt + 1 

下面是該文件的兩行我想讀:

Jan 10 09:32:46 j4-be03 sshd[3885]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root 
Jan 10 09:32:48 j4-be03 sshd[3885]: Failed password for root from 218.241.173.35 port 50212 ssh2 
+0

你想要所有的登錄嘗試或只是失敗的?請更新問題和標題(它太籠統了),使其更清晰。 – jcollado 2012-02-15 13:11:33

回答

1

幾個答案,這裏會給你你所需要的,但如果你想更有效地做到這一點:

from __future__ import with_statement # needed in python 2.5 and earlier 
import re 
from itertools import ifilter 

def count_root(file, regex=re.compile('root')): 
    count = 0 
    with open(file, 'r') as src: 
     for i in ifilter(regex.search, src): 
      count += 1 
    return count 

print count_root('file') 

雖然你肯定可以調整該正則表達式,讓您更準確的結果。如果你能夠大幅縮小它的範圍(比如root必須在最後30個字符,或者你有什麼),那麼目標字符串方法會更快。

0

像這樣的東西應該work--您可能需要調整regular expression以滿足您的確切需求:

myFile = open('file') 
count_rr = 0 
for line in myFile: 
    if re.search('pam_unix\(sshd:auth\): .* user=root ', line): 
     count_rr += 1 
4

這絕對不是最c ompact或python-y的方式來做到這一點,但它應該工作。我只是不確定[?]在代碼中做了什麼,用冒號代替:它應該可以工作。

雖然你可能會得到一些誤報!

(我個人在bash做到這一點:

grep -c 'sshd\[.*authentication failure.* user=root ' file 

應該做的伎倆(更堅固)

0

我想你可以嘗試這樣的事:

count_rr = len(line for line in myFile 
       if 'Failed password for root' in line) 

備註:

  • 如果文件很大,請勿使用readlines,只需遍歷文件對象以避免將整個文件存儲在內存中。
  • 您可以使用in運算符直接查找子字符串,不需要拆分該行。