#!/bin/bash # # If a workstation is not used for a certain amount of time, take an action # such as hibernate, suspend or shutdown. # # Desktop manager such as Gnome and KDE typically have options to do that, # but it only works when a use stays logged in. This script only works when # no user is logged in. # # This script checks how many people are logged using who(1) and record # the result in a file in /var. If the count is zero twice in a row # (using the value in the file to know what the count was the last time) # it means nobody has logged in during the interval and action is taken. # # Run this script through cron, and set the interval based on what you think # is reasonable, for example if you run the script every 5 minutes, and # nobody logs in for 5 to 10 minutes, the machine will hibernate (or suspend, # or shutdown) automatically. # # For example, to shutdown after 5 minutes with Paul Vixie's cron, # use a line such as: # # 0-59/5 * * * * /usr/local/bin/action_if_nobody.bash hibernate # # # Copyright Yves Dorfsman, Calgary, 2008 # if [[ $# -ne 1 ]] ; then echo -e "\nThis script requires one argument.\n" >&2 exit 1 fi case $1 in # This script should be run as root, so we use the pm utils # from sbin hibernate) ACTION="/usr/sbin/pm-hibernate" ;; suspend) ACTION="/usr/sbin/pm-suspend" ;; shutdown) ACTION="/sbin/shutdown -hy now" ;; *) echo -e "\nThe argument can only be hibernate, suspend or shutdown.\n" >&2 exit 1 esac # We use /var/run to prevent non-root users to touch the file COUNTFILE=/var/run/who_count WHO=/usr/bin/who ACTION_NOW=0 WHO_COUNT_NOW=$($WHO |wc -l) # If there is no file, we don't know the last count, so we skip if [[ -f $COUNTFILE ]] ; then WHO_COUNT_LAST=$(head -1 $COUNTFILE) # Was the content of the file valid ? echo $WHO_COUNT_LAST |egrep '^([0-9])+$' >/dev/null 2>&1 if [[ $? -eq 0 ]] ; then echo who count last $WHO_COUNT_LAST echo who count now $WHO_COUNT_NOW let TOTAL=WHO_COUNT_LAST+WHO_COUNT_NOW echo totalw $TOTAL if [[ TOTAL -eq 0 ]] ; then ACTION_NOW=1 fi fi fi echo $WHO_COUNT_NOW > $COUNTFILE (( $ACTION_NOW )) && $ACTION