I have been asked to write a program using python 开发者_运维知识库for an assignment.
I have been given a syslog file and I have to find things out about it
How do I find out how many attempts were made to login to the root account?
Any advice would be highly appreciated as I am very new to python and completely lost!
You want /var/log/auth.log
, not syslog.
It'll contain lines like like this:
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
Basic, naive code to accomplish the problem would be as follows:
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
Like user calmh suggested, it will probably be better long-term to parse with regular expressions, but if you don't know them already, it can be non-trivial to learn.
something like this
#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
You probably need to read the file, parsing each line. When you find a line that matches what you're interested in (failed root login, for example), you increment a counter.
Take a look at how to read files and possibly how to use regular expressions.
If you are going to do this check against a "live" log file, say every five minutes, you need to keep track of how much of the file you have already processed so you don't read it all every time. This is slightly more complicated, because you need to remember state (file size) between executions. In that case, look at the shelve
module.
精彩评论