2012-02-15 213 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运算符直接查找子字符串,不需要拆分该行。