Ruby one-liner to count logins in Linux last command

count logins in last command

If you want to take the output of the Linux last command, and get a count of how many times each user connected to your server, this script will do.

sample input

tommytrojan      sshd         abc.def Fri May 15 13:30 - 13:30  (00:00)joebruin      sshd         ddd.eee Fri May 15 13:30 - 13:30  (00:00)joebruin      sshd         ddd.eee Fri May 15 13:30 - 13:30  (00:00)janebruin      sshd         ddd.eee Fri May 15 13:30 - 13:30  (00:00)

sample output

Total entries: 4joebruin = 2janebruin = 1tommytrojan = 1

script and explanation

last | ruby -ane 'BEGIN{rows=0; a={}}; next if $F[0].nil?; a[$F[0]]||=0;a[$F[0]]+= 1; rows += 1; END{puts "Total entries: #{rows}" ; a.sort_by{|k,v|v}.reverse.each{|k,v| puts "#{k} = #{v}"} }'

NOTE: My colleague did the same thing in this shell script. And his script includes the line with the missing user field.

last | cut -d" " -f1 | sort | uniq -c | awk '{print $1" " $2}' | sort -nr


Revision #3
Created 2015-05-15 21:05:31 UTC by Franks, Mike
Updated 2015-05-15 21:15:03 UTC by Franks, Mike