Alain's Blog

  1. 首页
  2. Openwrt
  3. 正文

Openwrt使用Qemu-GA

2021年3月22日 2169点热度 3人点赞 0条评论

Openwrt

转载请注明出处,本文仅用于交流,如有不对的地方,恳请指正

背景

很多朋友在使用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来测试是否可以正常关机。

标签: Openwrt Proxmox VE Qemu Qemu-GA Qemu-Guest-Agent
最后更新:2021年3月22日

Alain

看了我的文,就是我的人,点个赞再走成不成

点赞
下一篇 >

文章评论

取消回复

文章目录
  • 背景
  • 自定义shutdown命令

COPYRIGHT © 2022 Alain's Blog. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang