Python读取文件

Python读取文件,python,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 下面是我试图读

我如何知道有多少次尝试使用根帐户登录

以下是我目前在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

类似这样的方法应该会起作用--您可能需要调整以满足您的确切需要:

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

这肯定不是实现这一点的最紧凑或python-y方式,但它应该可以工作。我只是不确定[?]在代码中做了什么,用冒号替换它:它应该可以工作

你可能会得到一些误报

(就我个人而言,我会在bash中这样做:

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

应该做到这一点(而且更加健壮)

我想你可以试试这样的方法:

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

  • 如果文件很大,不要使用
    readlines
    ,只需在file对象上迭代,以避免将整个文件存储在内存中
  • 您可以使用中的
    操作符直接查找子字符串,无需拆分行

这里有几个答案可以满足您的需要,但如果您想更有效地实现这一点:

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个字符中,或者你已经做了什么),则目标字符串方法会更快。

您想要所有登录尝试还是只想要失败的登录尝试?请更新问题和标题(太笼统了),以便更清楚。