views:

278

answers:

3

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!

A: 

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.

calmh
+1  A: 

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.

lfaraone
About the `/var/log/auth.log` bit, that's highly system dependent; on Solaris there is no such file, for example. The syntax will also probably vary from OS to OS.
calmh
A: 

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
ghostdog74
Don't count on `close` getting called manually. *Always* use a context manager (`with open("mysyslogfile") as f:`) when possible.
Mike Graham
yes, do that when possible. but my solution works in older version of Python without "with" support. :)
ghostdog74
@ghostdog, No, your solution is bug-prone. In pre-2.5 Python, you should always call close in a finally block.
Mike Graham
If you want to do that, that's fine, but no , there's no need to.
ghostdog74