GracefulRestart's awk solution to the question is excellent; as you noted in your comments to his answer the last
command isn't quite granular enough. But, assuming that auth.log
on debian is similar enough to what I see on Ubuntu you could so some maths based on the data there.
I appreciate that this is not an answer, but it still may be useful to you.
I filtered a bunch of lines out of /var/log/auth.log
, they pertain to both local and ssh logins.
cat auth.log
2018-12-06T07:28:00.487714+13:00 server systemd-logind[944]: New session 2597 of user tink.
2018-12-06T08:34:16.360766+13:00 server login[29537]: pam_unix(login:session): session opened for user tink by LOGIN(uid=0)
2018-12-06T08:34:16.372714+13:00 server systemd-logind[944]: New session c4 of user tink.
2018-12-06T08:34:20.960596+13:00 server login[29537]: pam_unix(login:session): session closed for user tink
2018-12-06T08:36:01.197712+13:00 server systemd-logind[944]: Removed session 2597.
Here's a (convoluted) awk-script ..
cat session.awk
{
if( $0 ~ /systemd-logind.+New session/ && $0~user ){
start[$6]=$1
}
if( $0 ~ /systemd-logind.+ Removed session/ && start[gensub(/([0-9]+).*/, "\\1", "1", $6)] != "" ){
tmp = start[gensub(/([0-9]+).*/, "\\1", "1", $6)]
cmd = "date +%s -d ";
cmd $1 | getline outa;
cmd " " tmp | getline ina;
close( cmd )
printf "%s was logged in for %s seconds\n", user, outa-ina
}
if( $0 ~ /login.+ session opened/ && $0~user ){
start[gensub(/[^0-9]+([0-9]+).*/,"\\1","1",$3)]=$1
}
if( $0 ~ /login.* session closed/ ){
tmp = start[gensub(/[^0-9]+([0-9]+).*/,"\\1","1",$3)]
cmd = "date +%s -d ";
cmd $1 | getline outa;
cmd " " tmp | getline ina;
close( cmd )
printf "%s was logged in for %s seconds\n", user, outa-ina
}
}
Running that against the snippet above:
awk -v user=tink -f session.awk sessions
tink was logged in for 4 seconds
tink was logged in for 4081 seconds
last
command" -- does that mean you'd be satisfied with a (potential) answer of "You can't", and that a post-processing answer (along the lines oflast | some code
) would be unacceptable ? – Jeff Schaller♦ Dec 4 '18 at 19:12