TS453Bmini是威联通一款性价比很高的产品,买了Nas后经历了几次意外断电,担心对硬盘不好,于是买了个UPS。带通知Nas关机功能的UPS毕竟贵,于是买了个低价的不带管理功能的UPS,使用Python脚本通过ping路由的方式来检测是否断电,连续几分钟ping不通路由后就执行关机。
该脚本会每隔一分钟ping一次路由,失败后会往系统Log中写入一条警告信息,连续失败几次后会执行关机命令并且往系统Log中写入一条错误信息:
import platform # For getting the operating system name
import subprocess # For executing a shell command
import sys
import threading
import time
from time import sleep
failCount = 0
routerAddress = "192.168.1.1"
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower() == 'windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
def shut_down():
return subprocess.call(["poweroff"]) == 0
def check_power(host):
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
result = ping(host)
global failCount
if not result:
failCount += 1
log("ping fail", "1")
if failCount > 6:
log("ping fail for 8 minutes, nas will shutdown", "2")
if shut_down():
log("shutdown execute successfully", "0")
sys.exit()
else:
log("shutdown execute fail", "1")
else:
failCount = 0
def log(msg, level):
print(msg)
subprocess.call(["log_tool", "-a", msg, "-t", level, "-N", "Power Check", "-G", "Power"])
if __name__ == '__main__':
log("Check power start!", "0")
while True:
threading.Thread(target=check_power(routerAddress), name='CheckPowerThread').start()
sleep(60)
将上面的代码保存成auto_power_off.py
(修改文件中routerAddress
为你的路由地址),放在第一块硬盘的software目录下,在终端中使用命令/usr/local/bin/python /share/CACHEDEV1_DATA/software/auto_power_off.py > /dev/NULL &
即可启动脚本(具体路径可能不一样,以实际路径为准),启动后脚本会一直在后台运行,每隔一分钟检测一次和路由器的连接情况,连续失败7次后(大约8分钟)就自动关机。
现在脚本在后台运行了,那我怎么知道它是不是运行良好呢?这个问题很简单,只需要使用终端连接上Nas,执行ps |grep auto_power_off
命令,如果结果里有类似下面这两行结果,就说明脚本在后台正常运行:
16758 admin 7168 S /usr/local/bin/python /share/CACHEDEV1_DATA/software/auto_power_off.py
26614 admin 1092 S grep auto_power_off
脚本有了,还需要保证脚本能稳定执行,一开始我用的方案是在开机启动脚本中启动该脚本,后来有一天发现后台进程不见了,也记不清是我测试的时候杀了进程后忘了开还是后台进程遇到问题挂掉了。这个问题促使我寻找更稳定的解决方案,于是就想到了通过定时任务来检测后台进程,每两分钟检查一次,如果后台进程挂掉,就重启它:
auto_power_off_deamon.py
import subprocess # For executing a shell command
def log(msg, level):
print(msg)
subprocess.call(["log_tool", "-a", msg, "-t", level, "-N", "Power Check", "-G", "Power"])
if __name__ == '__main__':
output = subprocess.check_output(["ps"])
# print(output)
if "auto_power_off.py" not in output:
log("Check power thread dead! Starting again!", "1")
subprocess.call(["/bin/sh", "/share/CACHEDEV1_DATA/software/start_check_power.sh"])
# else:
# print("Check power OK")
start_check_power.sh
#!/bin/sh
/usr/local/bin/python /share/CACHEDEV1_DATA/software/auto_power_off.py > /dev/NULL &
将这两个文件都放在software目录下,并且给start_check_power.sh
添加运行权限,并且设置定时任务,编辑/etc/config/crontab
添加以下规则:
*/2 * * * * /usr/local/bin/python /share/CACHEDEV1_DATA/software/auto_power_off_deamon.py
执行crontab /etc/config/crontab && /etc/init.d/crond.sh restart
重启crontab。
OK,一切都搞定了,拔掉网线试试吧!
文件下载地址:https://github.com/fengmlo/Qnap-auto-power-off