shell之KVM虛擬機管理

關於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也就不可用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章