Here is the simplest way to shutdown Linux Box like NAS when AC Power off.
Same crontab bash script is attached for Debian 6.0 squeeze.
You should buy a cheap UPS, such as APC BK500 at about CNY ¥238 (about USD $40, price at www.newegg.com.cn at 2012-02-14).
My way is checking the Gateway’s response, which Gateway is not attached to the UPS. So when AC PowerOff, the Gateway is off line either.
When NAS got no response from the Gateway, do shutdown in 3mins, but if Gateway recovered in 3mins, the shutdown is cancled.
Here we go:
- Add:
*/2 * * * * /etc/cron/cron.d/luis_upscheck - In /etc/cron/cron.d/luis_upscheck , make it executable by “chmod +x”
- Here is the bash script:
#!/bin/bash
## Author [email protected] at 2012-02-14
## check ping for ups every 2 mins, if down, shutdown in 3 mins, if ok within 2 mins, recover shutdown
## while true
## do
## get the gateway IP
GWIP=’127.0.0.1′
let n=0
for x in `/sbin/route | grep default`
do
if [ $n -eq 1 ]
then
GWIP=$x
break
fi
let n=n+1
done
ping -c 1 $GWIP > /dev/null
ret=$?
if [ $ret -eq 0 ]
then
# $ret = 0
# router is OK
#echo “Router is UP!”
## sleep 10
pscnt=`ps | grep halt | grep -v grep | wc -l`
if [ $pscnt -gt 0 ]
then
echo “Luis_UPS: AC Power/Network Recovered! Cancel shutdown!”
##/sbin/shutdown -c “Luis_UPS: AC Power/Network Recovered! Cancel shutdown!” &
/usr/bin/killall halt
fi
else
# $ret = 1
# if router fail, it meas 220V is down, or network is down
echo “Luis_UPS: AC Power/Network Failed! Ready to shutdown in 180s!”
pscnt=`ps | grep halt | grep -v grep | wc -l`
if [ $pscnt -eq 0 ]
then
# if no shutdown in progress, then shutdown
echo “Luis_UPS: AC Power/Network Failed! Ready to shutdown in 3 mins!”
##/sbin/shutdown -h 3 “Luis_UPS: AC Power/Network Failed! Ready to shutdown!” &
/sbin/halt -d 180 &
fi
fi
## done - Reboot the box.
- You can use infinite loop of while(1) with sleep for non-crontab usage.
- You can download the bash script here: luis_upscheck .
- Here is the Debian 6.0 version bash script: luis_upscheck , using crontab to make it run like:
*/2 * * * * root /bin/bash /root/luis_upscheck - Good luck.