Unfortunately you did not specify your specific requirements, so it's hard to know, what exactly you need.
However with shell scripts almost anything is possible. I have a shell script that shutdowns the computer, once specific clients (space separated list in the CLIENTS variable) are no longer online and certain processes (space separated list in the PROCESSES variable) are not running for the last 3 checks:
#!/bin/sh
LOGFILE=/var/log/autoshutdown.log
CLIENTS="hanzo twix"
PROCESSES="screen"
CHECK_THRESHOLD=3
CHECK_COUNT_FILE=/tmp/autoshutdown_count
FALSE=1
TRUE=0
function log() {
typeset message="$1"
echo "$(date +'%Y-%m-%d %H:%M:%S') $message" >> $LOGFILE
}
function clientsOnline() {
typeset flag_online=$FALSE
for client in $CLIENTS
do
if ping -c 1 $client 1>/dev/null 2>/dev/null
then
#log "Client $client is online."
flag_online=$TRUE
else
#log "Client $client is offline."
true
fi
done
return $flag_online
}
function processRunning() {
typeset process_flag=$FALSE
for process in $PROCESSES
do
if ps -e | grep -qs $process
then
#log "Process $process is running."
process_flag=$TRUE
else
#log "Process $process is not running."
true
fi
done
return $process_flag
}
function resetShutdownCounter() {
echo "0" > $CHECK_COUNT_FILE
}
function getShutdownCount() {
if [ -r $CHECK_COUNT_FILE ]
then
cat $CHECK_COUNT_FILE | head -n 1
else
echo 0
fi
}
function incrementShutdownCounter() {
echo $(expr $(getShutdownCount) + 1) > $CHECK_COUNT_FILE
}
if [ $(id -u) -ne 0 ]
then
echo "This script must be run as root user." >&2
exit 1
fi
#log "### Starting ###"
if clientsOnline
then
#log "At least one client is online. Reseting shutdown count."
resetShutdownCounter
elif processRunning
then
#log "At least one of the registered processes is running. Reseting shutdown count."
resetShutdownCounter
else
incrementShutdownCounter
log "No registered client online. Shutdown counter incremented. Current value: $(getShutdownCount)"
if [ $(getShutdownCount) -ge $CHECK_THRESHOLD ]
then
log "Shutdown count threshold reached. Shutting down system in 10 seconds."
rm -f $CHECK_COUNT_FILE
/sbin/shutdown -h 1
fi
fi
All you have to do is to run this script from your crontab every 5 minutes. Then it would shutdown your computer in case the shutdown conditions are fulfilled for 15 minutes in a row.
Cheers Yaba, Very useful example script; general enough for me to simply modify as needed. Thanks – Ashimema – 2011-01-19T21:51:12.213
Only just got round to playing with this...
In your script where do the "clients" actually come from? It's probably a basic Linux question, but where's the link between the friendly "Client" name you use here and the client machines physical address (IP)? – Ashimema – 2011-02-09T16:04:44.223
@Ashimema... that's a simple host name resolution through DNS or /etc/hosts. You could also enter an IP address instead of the host name. Basically the command 'ping -c 1 $client' must succeed in case the client is online. – Yaba – 2011-02-09T21:56:56.287