编写脚本 vm_test.sh 可以使用vm_test.sh 命令来 进行 ,安装, 删除虚拟机 ,启动和关闭虚拟机,重置虚拟机,对虚拟机进行快照功能
vim /bin/vm_test.sh
#!/bin/bash
case "$1" in
start)
virsh start $2 &> /dev/null
virt-viewer $2 &> /dev/null ##启动desktop虚拟机
;;
stop)
virsh destroy $2 ##关闭desktop虚拟机
;;
install)
virt-install \
--name $2 \
--ram 1024 \
--file /var/lib/libvirt/images/$2.qcow2 \ ##安装虚拟机
--file-size 8 \
--location http://172.25.254.66/rhel7.2 \
--extra-args "ks=http://172.25.254.66/ks.cfg" &
;;
reset)
virsh destroy $2
rm -fr /var/lib/libvirt/images/$2.qcow2 ## 对虚拟机 进行重新快照来完成虚拟机的重置
qemu-img create -f qcow2 -b /var/lib/libvirt/images/$3.qcow2 /var/lib/libvirt/images/$2.qcow2
virsh start $2
virt-viewer $2
;;
remove)
virsh destroy $2
virsh undefine $2
rm -fr /var/lib/libvirt/images/$2.qcow2 ##删除虚拟机
;;
mksnapshot)
virsh destroy $2
virsh undefine $2
qemu-img create -f qcow2 -b /var/lib/libvirt/images/$2.qcow2 /var/lib/libvirt/images/$3.qcow2 ##对虚拟机进行快照
virt-install \
--name $3 \
--ram 1024 \
--file /var/lib/libvirt/images/$3.qcow2 \
--import &
;;
esac
测试:
使用vm_test.sh install 安装 名叫haha的虚拟机
使用vm_test.sh remove 删除 名叫hello的虚拟机
使用vm_test.sh start / stop 启动和关闭 名叫desktop的虚拟机
使用vm_test.sh mksnapshot 对名叫haha的虚拟机进行快照并调入前端管理 启动
使用vm_test.sh reset 对名叫haha的虚拟机 进行重新快照node1 来完成虚拟机的重置