Python - 从syslog文件中检索信息

时间:2010-03-20 14:40:38

标签: python login count syslog

我被要求用python编写一个程序来编写一个程序。

我已经获得了一个syslog文件,我必须找到关于它的事情

如何查看登录root帐户的尝试次数?

任何建议都会受到高度赞赏,因为我对python很新并且完全丢失了!

3 个答案:

答案 0 :(得分: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

就像用户冷静建议的那样,用正则表达式解析可能会更好,但如果你已经不知道它们,那么学习它可能并非易事。

答案 1 :(得分:0)

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

查看how to read files,可能how to use regular expressions

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

答案 2 :(得分: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
相关问题