Manually UPS check for all linux BOX

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:

  1. Add:
    */2 * * * * /etc/cron/cron.d/luis_upscheck
  2. In /etc/cron/cron.d/luis_upscheck , make it executable by “chmod +x”
  3. 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
  4. Reboot the box.
  5. You can use infinite loop of while(1) with sleep for non-crontab usage.
  6. You can download the bash script here: luis_upscheck .
  7. 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
  8. Good luck.
发布日期:

发表评论