Help

Help

Post by Linda Vermon » Fri, 19 Dec 1997 04:00:00



Did anyone know how to use who and date to write a program
that prints the number of hours and minutes that a user has been logged
on to
the system
Thank

 
 
 

Help

Post by Lawson Hans » Sat, 20 Dec 1997 04:00:00



>Did anyone know how to use who and date to write a program
>that prints the number of hours and minutes that a user has been logged
>on to
>the system
>Thank

Yes, but you're going to have to do a little bit of shell
script writing/testing.

The output of the "who" command contains the date and time
at which users logged on to the system, and the "date" command
returns the date and time of the instant it is run, so what you
need to do is take the difference of those two values.

To cover all of the possibilities you would need to check
that the two different date/time items (I'll call them
"logon_time", and "current_time") are from the same year
(otherwise you need to handle that), and from the same
month of the same year (otherwise you need to handle that),
and from the same day of the same month of the same year
(otherwise you need to handle that), but if you can guarantee
that always log off from the system at a time that is later
in the same day as that day on which they logged on, then
the whole program becomes much simpler, but still not
entirely trivial, since you have to do modulo 60 arithmetic.

On our system, the fifth column of the output of the "who"
command is the "logon_time" in the format "HH:MM", and you
can use different options of the "date" command to return
the "current_time" in hours and minutes like that too.

For example:
#---------->8----------Cut Here----------8<----------
#!/bin/sh

USER="vky7qbc"
CURR_TIME=`date +%H:%M`

# get the first line of output of "who" for some USER,
# and "set" it into the shell's positionsl parameters
#
set `who | grep ${USER} | head -1`

LOGON_TIME=$5

# Set the shell's Input Field Separator to a colon (i.e.: ':')
#
IFS=':'

set $LOGON_TIME

LOG_HRS=$1
LOG_MINS=$2

set $CURR_TIME

CURR_HRS=$1
CURR_MINS=$2

if [ ${CURR_MINS} -lt ${LOG_MINS} ]
then
    CURR_HRS=`expr ${CURR_HRS} - 1`
    CURR_MINS=`expr ${CURR_MINS} + 60`
fi

HRS=`expr ${CURR_HRS} - ${LOG_HRS}`
MINS=`expr ${CURR_MINS} - ${LOG_MINS}`

if [ $HRS -eq 1 ]
then
    HOURS="${HRS} hour"
else
    HOURS="${HRS} hours"
fi

if [ $MINS -eq 1 ]
then
    MINUTES="${MINS} minute"
else
    MINUTES="${MINS} minutes"
fi

echo "User: ${USER} has been logged on for: ${HOURS} and ${MINUTES}"
#---------->8----------Cut Here----------8<----------

I think that should work.

I hope that helps.

Best regards,

Lawson Hanson