简体   繁体   中英

Modify the output of the command “last”

I want to make a program in bash to display the output of last with this format:

username | number of sessions | duration of sessions | maximum session length

I already did the first two columns but don´t know how to do the rest. This is the code I wrote for the username and number of sessions:

            last |& tee  last.txt
            cut -d' '  -f1,2  last.txt > last1.txt

thanks

You can try with something like this. Its not perfect but very close:

#!/bin/bash

unique_users="$( last | awk ' {print $1} ' | sort | uniq | grep -v 'shutdown\|wtmp\|reboot' | awk 'NF' )"

for user in $unique_users
do
    number_of_sessions="$( last $user | awk '{print $NF}' | grep '^(' | tr -d '()' | wc -l )"
    total_mins="$( last $user | awk '{print $NF}' | grep '^(' | tr -d '()' | awk '{ split($1, t, ":"); print (t[1]*60+t[2]) }' | awk '{ sum+=$1}END{print sum/60}' )"
    max_length="$( last $user | awk '{print $NF}' | grep '^(' | tr -d '()' | awk '{ split($1, t, ":"); print (t[1]*60+t[2]) }' | sort -rn | head -1 | awk '{ sum+=$1}END{print sum/60}')"
    printf "$user | $number_of_sessions | $total_mins | $max_length\n"
done

Regards!

I'm assuming last output same as Mint19

owner    tty7         :0               Sun Nov 17 06:18    gone - no logout
owner    tty7         :0               Sun Nov 10 11:13 - crash (6+18:34)
owner    tty7         :0               Thu Nov  7 14:10 - 11:11 (2+21:00)
owner    pts/1        :0               Wed Nov  6 21:48 - 21:48  (00:00)
owner    pts/1        :0               Wed Nov  6 21:37 - 21:40  (00:03)

The file is sorted by timestamp, and the 10th column contain the session duration: either (HH:MM), or (DAYS+HH:MM). Small awk will do the trick. Script only count terminated session - ignoring crashed/still running sessions.

Total is session time in minutes.

#! /usr/bin/awk -f
{
    id=$1
    if ( match($10, /\(([0-9]+)\+\)?([0-9][0-9]):([0-9][0-9])/, a) ) {
        dur_min = a[1]*24*60 + a[3] * 60 + a[4] ;
        s_count[id]++ ;
        s_total[id] += dur_min
        if ( dur_min > s_max[id] ) s_max[id] = dur_min
    }
}

END {
    print "ID", "Count", "Total(min)", "Max(min)"
    for (id in s_count) {
         print id, s_count[id], s_total[id], s_max[id]
    } ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM