Python - 从syslog文件中获取信息

1 投票
3 回答
6639 浏览
提问于 2025-04-15 20:38

我被要求用Python写一个程序来完成一个作业。

我拿到了一份系统日志文件,现在需要从中找出一些信息。

我该怎么查找有多少次尝试登录根账户的记录呢?

如果能给我一些建议,我会非常感激,因为我对Python还很陌生,完全不知道从哪里开始!

3 个回答

0

你可能需要读取文件,逐行分析。当你找到一行符合你关注的内容时(比如失败的根用户登录),就把计数器加一。

可以看看如何读取文件,还有可能需要了解如何使用正则表达式

如果你打算每五分钟检查一次“实时”的日志文件,你需要记住你已经处理了文件的多少部分,这样就不会每次都读取整个文件。这会稍微复杂一点,因为你需要在每次执行之间记住状态(文件大小)。在这种情况下,可以看看shelve模块。

1

你需要的是 /var/log/auth.log,而不是 syslog。

这个文件里会有像这样的内容:

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

就像用户 calmh 提到的,长期来看,使用正则表达式来解析可能会更好,但如果你还不熟悉正则表达式,学习起来可能会有点难。

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

撰写回答