Reputation: 1323
How would I find out how many attempts have been made to login with the root account?
Here is the code I am using so far in python:
myFile = open('file','r')
count_rr = 0
for line in myFile.readlines():
list_of_line = line.split(' ')
if 'root' in list_of_line[?]
print 'root'
count_rr = counter_rt + 1
Here are two lines of the file I am trying to read:
Jan 10 09:32:46 j4-be03 sshd[3885]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.241.173.35 user=root
Jan 10 09:32:48 j4-be03 sshd[3885]: Failed password for root from 218.241.173.35 port 50212 ssh2
Upvotes: 3
Views: 268
Reputation: 724
Several answers here will give you what you need, but if you want to do it more efficiently:
from __future__ import with_statement # needed in python 2.5 and earlier
import re
from itertools import ifilter
def count_root(file, regex=re.compile('root')):
count = 0
with open(file, 'r') as src:
for i in ifilter(regex.search, src):
count += 1
return count
print count_root('file')
Although you could definitely tune that regex to give you more accurate results. And if you were able to narrow it down considerably (like root must be in the last 30 characters, or what have you), then targeted string methods would be quicker still.
Upvotes: 1
Reputation: 40414
I think you can try something like this:
count_rr = len(line for line in myFile
if 'Failed password for root' in line)
Notes:
readlines
, just iterate over the file object to avoid having the whole file in memory.in
operator to look for substrings directly, there's no need to split the line.Upvotes: 0
Reputation: 9980
It's definitely not the most compact or python-y way to do this, but it should work. I'm just not sure what the [?] is doing in your code, replace that by a colon : and it should work.
you might get some false positives though!
(Personally I would do this in bash:
grep -c 'sshd\[.*authentication failure.* user=root ' file
should do the trick (and is more robust)
Upvotes: 4
Reputation: 249552
Something like this should work--you may want to adjust the regular expression to suit your exact needs:
myFile = open('file')
count_rr = 0
for line in myFile:
if re.search('pam_unix\(sshd:auth\): .* user=root ', line):
count_rr += 1
Upvotes: 0