Python读取文件

3

我该如何查找使用root账户登录的尝试次数?

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

你想要所有的登录尝试记录还是只想要失败的记录?请更新问题和标题(它太泛泛了)以使其更清晰明了。 - jcollado
4个回答

4

这绝对不是最紧凑或最符合Python风格的方法,但它应该有效。我只是不确定你代码中的[?]是什么意思,请用冒号:替换它,然后它应该可以工作。

但你可能会得到一些错误结果!

(个人建议用bash实现:

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

应该能解决问题(并且更加健壮)。

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')

虽然你可以调整正则表达式以获得更准确的结果。如果你能够大大缩小范围(比如根必须在最后30个字符内,或者其他限制),那么有针对性的字符串方法仍然会更快。


0

类似这样的代码应该可以运行 - 你可能需要调整正则表达式以满足你的实际需求:

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

0

我认为你可以尝试这样做:

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

注意事项:

  • 如果文件很大,请勿使用readlines,而是迭代文件对象以避免将整个文件存储在内存中。
  • 您可以使用in运算符直接查找子字符串,无需拆分行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接