|
How to write a shell script that checks and reports
on who logs in and who logs out?
The who command gives time when the user logged in. Coding: $ LANG=C who -s gssjgu:/g/g00k00/gssjgu/TMP> LANG=C who -s gssjgu pts/1 Jul 4 15:06 (1.1.1.11) getk00 pts/2 Jul 4 08:54 (1.1.1.2) gti001 pts/3 Jun 22 15:38 (1.1.1.39) $ The following script display information’s about users who logged in since n minutes (n can be specified as a parameter of the script, the default value is 5). Coding: $ cat log5.sh #!/usr/bin/ksh typeset -i SINCE=${1:-5} # # Get current date # date '+%Y +%m %d %H %M' | read year month day hour min # # Compute timestamp for current date minus $SINCE minutes # format 'mmddHHMM' ('cal' command usage) # (( min -= SINCE )) (( min < 0 )) && { (( min += 60 )) ; (( hour -= 1 )) } (( hour < 0 )) && { (( hour += 24 )) ; (( day -= 1 )) } (( day <= 0 )) && { (( month -= 1 )) (( month <= 0 )) && { (( month=12 )) ; (( year -= 1 )) } day=$(cal $month $year | tr '\n' ' ' | awk '{print $NF}') } ts5=$(printf "%02d%02d%02d%02d" $month $day $hour $min) # # Determine users logged on since $SINCE minutes # (Based on 'who -s' command)' # LANG=C who -s | awk -v ts5="$ts5" -F '[ \t:]*' ' function to_timestamp(month, day, hour, min) { m = index("___,jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec,", "," tolower(month) ",")/4; return sprintf("%02d%02d%02d%02d", m, day, hour, min); } to_timestamp($3, $4, $5, $6) >= ts5 ' $ Output: Coding: $ LANG=C date Wed Jul 4 15:22:04 DFT 2012 $ log5.sh $ log5.sh 30 gssjgu pts/1 Jul 4 15:06 (1.1.1.11) $ Notes: last command will give you the last logins including any current login. Try using the -n option for last n logins Coding: last -n Last searches back through the file /var/log/wtmp (or the file designated by the -f flag) and displays a list of all users logged in (and out) since that file was created. Names of users and tty's can be given, in which case last will show only those entries matching the arguments. Check out the man page for last. |
|
See Also
Have a Unix Problem
Unix Books :-
Return to : - Unix System Administration Hints and Tips (c) www.gotothings.com All material on this site is Copyright.
|