Python - 从syslog文件中获取信息
我被要求用Python写一个程序来完成一个作业。
我拿到了一份系统日志文件,现在需要从中找出一些信息。
我该怎么查找有多少次尝试登录根账户的记录呢?
如果能给我一些建议,我会非常感激,因为我对Python还很陌生,完全不知道从哪里开始!
3 个回答
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