我被要求使用 python 编写一个程序来进行分配。
我得到了一个系统日志文件,我必须找出有关它的信息
如何找出登录 root 帐户的尝试次数?
任何建议都将受到高度赞赏,因为我对 python 非常陌生并且完全迷失了!
你想要/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
就像用户冷静建议的那样,长期使用正则表达式进行解析可能会更好,但如果您还不了解它们,那么学习起来可能并非易事。
像这样的东西
#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