1

I am looking to write a BASH to monitor how long sessions of the given username have been logged on. Here is what I have so far. I want it to work as any user

( lastlog awk ' {print $1 } ' | tail -n +2)
do
NOW=$(date +%s)
USR=$(lastlog | awk '( print $1, $5, $6, $9 )' | grep $U)
USRDATE=$(echo $USR | cut -d":" -f2)
(( USRDATE = $(date --date ""$USRDATE" +%s) / 86400 ))
(( NOW = NOW / 86400 ))
(( DAYS = NOW - USRDATE ))
echo "The user $U: logged in $DAYs days ago"
done
0

1 Answer 1

1

I'd skip lastlog completely and look at the who command. This does practically everything you're asking:

$ who
oli      tty7         2013-09-20 14:33 (:0)
oli      pts/0        2013-09-20 14:33 (:0)
oli      pts/2        2013-09-21 22:00 (:0)
oli      pts/4        2013-09-25 20:09 (:0)
oli      pts/5        2013-09-24 11:02 (:0)

w is pretty good too but the login time is a bit more colloquial so not as well suited for scripting:

$ w
 20:13:15 up 5 days,  5:39,  5 users,  load average: 0.49, 0.53, 0.45
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
oli      tty7     :0               Fri14    5days  8:35m  0.03s /bin/sh /usr/bin/startkde
oli      pts/0    :0               Fri14    5days  0.00s  3:36  kdeinit4: kded4 [kdeinit]                      
oli      pts/2    :0               Sat22    3days  0.08s  0.08s /bin/bash
oli      pts/4    :0               20:09    3.00s  0.08s  0.00s w
oli      pts/5    :0               Tue11    5:45m  2:42   2:42  node /usr/bin/grunt watch
5
  • That's great, thanks. How would I write BASH to include the login of specific users? I have 5 users that I would like to check.
    – Macenbro
    Sep 26, 2013 at 0:21
  • @Macenbro who | awk '/user1|user2|user3|user4|user5/' - you could use grep but awk puts you in a good position if you want to a manipulate the output like: who | awk '/22|11/ {print $1 " " $3}'
    – Oli
    Sep 26, 2013 at 8:07
  • ./watchuser: line 3: syntax error near unexpected token newline' ./watchuser: line 3: case $1 in "0"'
    – Macenbro
    Sep 26, 2013 at 23:43
  • @Macenbro Comments aren't really suited for big code blocks. Either update your question (if it's still about this) or ask a new one if it's about something else.
    – Oli
    Sep 27, 2013 at 1:59
  • Sorry, I am new to the forum
    – Macenbro
    Sep 27, 2013 at 10:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .