转载请注明出处,本文仅用于交流,如有不对的地方,恳请指正
背景
很多朋友在使用Openwrt的时候,总是将其安装在Proxmox VE下,或者其他Qemu类的虚拟机中。
当Qemu-GA打开时,使用控制面板上的shutdown来关机是无法正常关机的,因为Openwrt本身并没有shutdown命令。
那么我们是否可以自定义一个shutdown命令来解决这个问题呢?答案明显是可以的。
自定义shutdown命令
使用ssh登陆到Openwrt
# 生成一个shutdown文件
touch /sbin/shutdown
# 赋予执行权限
chmod +x /sbin/shutdown
# 写入内容
nano /sbin/shutdown
在文本中写入以下内容
#!/bin/ash
# 默认使用关机命令
ACTION="poweroff"
# 默认倒数3s秒后执行命令
TIME="3s"
# 获取shutdown参数
# Qemu-GA 默认调用 -h -P +0的方式
while getopts "s:t:rkhncpP" OPT; do
case $OPT in
s|t)
TIME="${OPTARG:-"now"}"
;;
r)
ACTION="reboot"
;;
k)
ACTION="warning"
;;
h)
ACTION="halt"
;;
n)
ACTION="poweroff"
;;
c)
echo "Cancel shutdown, but not support the Openwrt!" > /dev/kmsg
ACTION="stop"
;;
p|P)
ACTION="poweroff"
;;
\?)
args=$@
echo "Unrecognized arguments received: $args" > /dev/kmsg
exit 1
;;
esac
done
echo "Shutdown Script: Set ACTION to $ACTION" > /dev/kmsg
echo "Shutdown Script: Set TIME to $TIME" > /dev/kmsg
time=`echo $TIME | tr -cd "[0-9]"`
timeUnit=`echo $TIME | tr -cd "[A-Za-z]"`
if [ ! -n "$timeUnit" ]; then
timeUnit="s"
fi
if [ "$timeUnit" = "s" ]; then
sleeptime=$time
elif [ "$timeUnit" = "m" ]; then
sleeptime=$(($time*60));
elif [ "$timeUnit" = "h" ]; then
sleeptime=$(($time*60*60));
elif [ "$timeUnit" = "d" ]; then
sleeptime=$(($time*60*60*24));
elif [ "$timeUnit" = "y" ]; then
sleeptime=$(($time*60*60*24*365));
else
echo "Invalid arguments unit: $TIME" > /dev/kmsg
exit 1
fi
echo "Shutdown Script: Waiting $TIME" > /dev/kmsg
while [ $sleeptime -gt 0 ];do
if [ "$sleeptime" = "1" ]; then
echo "Going Script!" > /dev/kmsg
else
echo "Please wait $(($sleeptime - 1))s" > /dev/kmsg
fi
sleep 1
sleeptime=$(($sleeptime - 1))
done
if [ $# == 0 ]; then
echo "Shutting down without any params" > /dev/kmsg
/sbin/poweroff
elif [ "$ACTION" = "poweroff" ]; then
/sbin/poweroff;
elif [ "$ACTION" = "reboot" ]; then
/sbin/reboot
elif [ "$ACTION" = "warning" ]; then
echo "关机警告" > /dev/kmsg
/sbin/poweroff;
elif [ "$ACTION" = "halt" ]; then
/sbin/halt
fi
保存上述代码之后,使用shutdown -h -P来尝试是否能够关机,出现倒计时则脚本执行正常,可以使用ctrl+c来取消,并在Proxmox VM控制面板中调用shutdown/reboot来测试是否可以正常关机。
文章评论