Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reading file

Tags:

python

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
like image 780
Stefan Avatar asked May 26 '26 10:05

Stefan


2 Answers

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)

like image 173
Claude Avatar answered Jun 01 '26 05:06

Claude


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.

like image 35
michaelfilms Avatar answered Jun 01 '26 05:06

michaelfilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!