Shell script Programming-case One
Programming Requirements:
1. Create a Vm-ctl script, under/bin/
2. Implement features: Create a virtual machine, create a virtual machine snapshot, turn on a virtual machine, display a virtual machine, stop a virtual machine, reset a virtual machine.
The script achieves the expected result:
SH vm-ctl create|nodecreate|start|view|stop|reset Vmname
The implementation script is as follows:
#!/bin/bash
Case "$" in
Create) # #创建虚拟机
Echo Create VM ...
Virt-install \
--name
--ram 1000 \
--FILE/VAR/LIB/LIBVIRT/IMAGES/$2.QCOW2 \
--file-size 8 \
--cdrom/home/kiosk/downloads/rhel-server-7.1-x86_64-dvd.iso &
Echo Create VM $ successful! Please create vmnode by nodecreate through this!!! # #创建完虚拟机之后, create a virtual machine snapshot and then use the virtual machine snapshot to operate.
;;
nodecreate) # #创建虚拟机快照
Virsh Destroy
Virsh undefine
Qemu-img create-f qcow2-b/var/lib/libvirt/images/$2.qcow2/var/lib/libvirt/images/
$2node.qcow2 &>/dev/null
Virt-install \
--name
--ram 1000 \
--DISK/VAR/LIB/LIBVIRT/IMAGES/$2NODE.QCOW2 \
--import &>/dev/null &
echo Create VM $2node successfull!!!
;;
Start) # #开启虚拟机
echo Start VM ...
Virsh Start $ &>/dev/null
Echo Start VM $ successful!!!
;;
View) # #显示虚拟机
Echo View VM ...
Virt-viewer $ &>/dev/null
Echo View VM $ successful!!!
;;
Stop) # #关闭/Stop virtual machine
echo Stop VM ...
Virsh Destroy $ &>/dev/null
Echo VM $ is stopped!!!
;;
Reset) # #重置虚拟机
echo Reset VM ...
Virsh Destroy $ &>/dev/null
Virsh Undefine $ &>/dev/null
Rm-fr/var/lib/libvirt/images/$2node.qcow2 # #删除原磁盘快照文件
Qemu-img create-f qcow2-b/var/lib/libvirt/images/$2.qcow2/var/lib/libvirt/images/
$2node.qcow2 &>/dev/null # #重新创建快照
Virt-install \ # #使用这个新快照创建虚拟机
--name
--ram 1000 \
--DISK/VAR/LIB/LIBVIRT/IMAGES/$2NODE.QCOW2 \
--import &>/dev/null &
Echo Reset VM $ successfule!!!
;;
*) # #其他, display error message
echo "Error:please input create|nodecreate|start|view|stop|reset after Vm-ctl"
Esac
Shell scripting "creation, opening, display, stop, reset of KVM virtual machines under Linux"