shell之KVM虚拟机管理

本文介绍了一个用于管理KVM虚拟机的bash脚本,包括创建、删除、重启等功能,并强调了在虚拟机关机和重启操作中ACPI服务的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于KVM虚拟机管理的脚本主要是通过virsh命令展开实现,在使用脚本之前需要封装母镜像及创建好第一个虚拟机。

在启动虚拟机时,我们通常通过start、shutdown、reboot等命令来进行,但是实际情况下,有时会发现使用shutdown、reboot命令进行关闭和重启虚拟机时无任何反应,而且利用状态返回值也是OK的。这时,我们在毫无办法的情况下就会想到暴力(destroy)关机。但是暴力关机这种方法我们也是不得已而为之,在网上查了一波资料后发现在使用shutdown、reboot时,虚拟机必须开启acpi服务。其中,ACPI表示高级配置和电源管理接口(Advanced Configuration and Power Management Interface),其原理是host通过发送acpi指令来控制虚拟机的电源,如果虚拟机系统没有安装acpi服务或该服务没有启动,那么虚拟机将不会重启或关闭,也就只有使用destroy 来强制关闭。以下是实现脚本

#!/bin/bash
#
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit 1
images=/var/lib/libvirt/images
case $1 in
        reset)
        virsh destroy $2
        rm -f $images/$2
        qemu-img create -f qcow2 -b $images/rhel6.5.img $images/$2
        virsh start $2
        ;;
        create)
        qemu-img create -f qcow2 -b $images/rhel6.5.img $images/"$2" &> /dev/null  || exit 1
        cd /etc/libvirt/qemu
        [ $? -eq 0 ] || exit 1
        [ -f "${2}.xml" ] &&  echo "${2}.xml already exists.. "  && exit 1 || {
                cp vm1.xml ${2}.xml
                sed -i  -e "s/vm1/$2/g" \
                        -e 's/<uuid>.*<\/uuid>//g' \
                        -e 's/<mac.*\/>//g' ${2}.xml
                virsh define ${2}.xml >/dev/null 2>&1
                action "$2 will be running.." /bin/true
                $0 start $2 #&> /dev/null
        }
        ;;
        delete)
        virsh destroy $2 >/dev/null 2>&1
        rm -f $images/$2 && \
        virsh undefine $2 &>/dev/null && \
        action "$2 delete successful." /bin/true || \
        action "$2 delete failed." /bin/false
        ;;
        start)
        virsh start $2 >/dev/null 2>&1 && \
        action  "$2 is started." /bin/true || \
        action  "$2 start failed." /bin/false
        ;;
        view)
        virt-viewer $2  &> /dev/null &
        ;;
        stop)
        virsh shutdown $2 >/dev/null 2>&1 && \
        action  "$2 is stop." /bin/true || \
        action  "$2 stop failed." /bin/false
        ;;
        reboot)
        virsh reboot $2 >/dev/null && \
        action "$2 is restarting" /bin/true || \

        action "$2 is restarting" /bin/  false     

        ;;
        enabled)
        virsh autostart $2
        ;;
        *)
        echo "Usages:$0 create|delete|reset|start|view|stop|reboot|enabled vm<number>  <==> vm create vm1"
        ;;
esac

在没有提供acpi服务时,关机使用destroy,这是reboot也就不可用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值