1

我被要求使用 python 编写一个程序来进行分配。

我得到了一个系统日志文件,我必须找出有关它的信息

如何找出登录 root 帐户的尝试次数?

任何建议都将受到高度赞赏,因为我对 python 非常陌生并且完全迷失了!

4

3 回答 3

1

你想要/var/log/auth.log,而不是系统日志。

它将包含如下行:

Mar 20 10:47:24 Opus su[15918]: pam_unix(su:auth): authentication failure; logname=lfaraone uid=1000 euid=0 tty=/dev/pts/25 ruser=lfaraone rhost=  user=root

完成该问题的基本、幼稚的代码如下:

loginattempts = {"root": 0,
                 "someuser": 0,} # Usernames you want to check
with open('/var/log/auth.log', 'r') as authlog:
    for line in authlog:
        if "authentication failure" in line:
            username = line.split('=')[-1] # split the string into an array, 
                                           # using '=' as the delimiter
            if username in loginattempts: # is the username one we care about?
                loginattempts[username] += 1

就像用户冷静建议的那样,长期使用正则表达式进行解析可能会更好,但如果您还不了解它们,那么学习起来可能并非易事。

于 2010-03-20T14:55:47.787 回答
0

您可能需要读取文件,解析每一行。当您找到与您感兴趣的内容匹配的行时(例如,root 登录失败),您增加一个计数器。

看看如何读取文件以及如何使用正则表达式

如果您要针对“实时”日志文件执行此检查,例如每五分钟一次,您需要跟踪您已经处理了多少文件,这样您就不会每次都读取它。这稍微复杂一些,因为您需要记住执行之间的状态(文件大小)。在这种情况下,请查看shelve模块。

于 2010-03-20T14:46:19.707 回答
0

像这样的东西

#open the file , can be /var/log/messages, /var/log/maillog etc as defined in your system
f=open("mysyslogfile")
count=0 
#go through the file
for line in f:
   if "<unique pattern for checking root account login>" in line:
       count+=1
#close the file
f.close()
print "total count: " ,count
于 2010-03-20T14:57:05.833 回答