Python to sort and count the uniq names from the file

Viewed 1058

I'm trying to read the log file in Linux /var/log/messages for a line having special pattern of strings which I have given below. From this line pattern I'm looking at the e-mail address for the user, like rajeshm@noi-rajeshm.fox.com and using the str.partition() method I'm separating it into two parts as a list index, and taking the first one further getting that split into a list for the ease of taking last index value, which is the user ID and that's working fine.

Saying that I'm able to get the list of users and total count but I need to count the occurrence of each user and print the user_name: Count, so the key and value.

Nov 28 09:00:08 foxopt210 rshd[6157]: pam_rhosts(rsh:auth): allowed access to rajeshm@noi-rajeshm.fox.com as rajeshm

#!/usr/bin/python3
f= open("/var/log/messages")
count = 0
for line in f:
  if "allowed access"  in line:
    count+=1
    user_id = line.partition('@')[0]
    user_id = user_id.split()[-1]
    print(user_id)
f.close()
print("--------------------")
print("Total Count :" ,count)

The current code is working as below:

bash-4.1$ ./log.py | tail
navit
akaul
akaul
pankaja
vishalm
vishalm
rajeshm
rajeshm
--------------------
Total Count : 790

While googling around I get the idea of using dictionary for this purpose and it's working as expected:

#!/usr/bin/python3
from collections import Counter
f= open("/var/log/messages")
count = 0
dictionary = {}
for line in f:
  if "allowed access"  in line:
    user_id = line.partition('@')[0]
    user_count = user_id.split()[-1]
    if user_count in dictionary:
        dictionary[user_count] += 1
    else:
       dictionary[user_count] = 1
for user_count, occurences in dictionary.items():
    print(user_count, ':', occurences)

And my output is as desired:

bash-4.1$ ./log2.py
rajeshm : 5
navit : 780
akaul : 2
pankaja : 1
vishalm : 2

I'm just looking if there is a better way around for this exercise.

2 Answers
Related