KVM脚本批量添加删除虚拟机
[背景]最近事情特別多,前段時間搞搞openstack,發現過與復雜,就想把KVM先好好學學,再過來搞它.因為工作關系,又用twisted開發了一個c/s的監控程序,但因還沒有寫完,所以暫時沒有發出來.如果不是強逼自己,我想我這個工具,也可能需要再等幾日才能發布吧.扯遠了,先不說這些,就說我這款工具能干嘛吧.簡單的說就像openstack的鏡像功能一般,不過,人家是提供Web Gui,點兩下就OK了,我這需要修改下配置文件vm.ini,不過它那個點兩下,不一定OK噢,反正我試過,沒那么靈光.我的配置文件很簡單,就是告訴我是添加還是刪除虛擬機,如果添加則需要告訴模板鏡像文件在哪?模板xml文件在哪.當然這些都是要定義好的.也就是提前將鏡像文件做好嘛.openstack的glance也是需要的嘛.
[過程]
(1)安裝模板系統
略
(2)將模板img文件和xml文件分別copy到/template/img,/template/xml下,當然,你也可以更改,不過,程序也需要做修改.
(3)修改vm.ini文件
參考
模板xml文件
more /template/xml/Template_Centos55x64_LAMP.xml
<!-- WARNING:?THIS?IS?AN?AUTO-GENERATED?FILE.?CHANGES?TO?IT?ARE?LIKELY?TO?BE OVERWRITTEN?AND?LOST.?Changes?to?this?xml?configuration?should?be?made?using:virsh?edit?Template_Centos55x64_LAMP or?other?application?using?the?libvirt?API. --> <domain?type='kvm'><name>Template_Centos55x64_LAMP</name><uuid>e7bbc1b0-e9b1-a0f2-bd1e-dd9f3fd48823</uuid><memory?unit='KiB'>524288</memory><currentMemory?unit='KiB'>524288</currentMemory><vcpu?placement='static'>2</vcpu><os><type?arch='x86_64'?machine='rhel6.3.0'>hvm</type><boot?dev='hd'/></os><features><acpi/><apic/><pae/></features><clock?offset='utc'/><on_poweroff>destroy</on_poweroff><on_reboot>restart</on_reboot><on_crash>restart</on_crash><devices><emulator>/usr/libexec/qemu-kvm</emulator><disk?type='file'?device='disk'><driver?name='qemu'?type='raw'/><source?file='/var/lib/libvirt/images/Template_Centos55x64_LAMP.img'/><target?dev='hda'?bus='ide'/><address?type='drive'?controller='0'?bus='0'?target='0'?unit='0'/></disk><interface?type='bridge'><mac?address='52:54:00:88:d0:51'/><source?bridge='br0'/><model?type='virtio'/></interface><serial?type='pty'><target?port='0'/></serial><console?type='pty'><target?type='serial'?port='0'/></console><input?type='mouse'?bus='ps2'/><graphics?type='vnc'?port='-1'?autoport='yes'/><video><model?type='cirrus'?vram='9216'?heads='1'/></video></devices> </domain>[root@localhost xml]# more /template/scripts/vm.ini
#Action,Vm_name,Template_img_file,Template_xml_file
add,web01,Template_Centos55x64_LAMP.img,Template_Centos55x64_LAMP.xml
delete,web01,none,none
現在我來做一個工作,就是添加兩個虛擬機,一個叫web01,一個叫web02
[root@localhost xml]# more /template/scripts/vm.ini
#Action,Vm_name,Template_img_file,Template_xml_file
add,web01,Template_Centos55x64_LAMP.img,Template_Centos55x64_LAMP.xml
add,web02,Template_Centos55x64_LAMP.img,Template_Centos55x64_LAMP.xml
執行腳本,結果:
[提供代碼]
#!/usr/bin/env?python ################################################################### #Auth:Zhuzhengjun #LastModified:2013/05/27 #Version?0.1 #Function?Description: #Batch?automatically?generated/delete?VM #1.Generated?VM ##1.1.Copy?VM?img?file ##1.2.Create?VM?XML?file ###1.2.1.Update?UUID ###1.2.2.Update?MAC ###1.2.3.Update?img?path ###1.2.4.Update?VM?Name #2.Start?VM #3.Delete?VM #################################################################### #import?module import?shutil import?os,sys from?virtinst.util?import?* import?libvirt import?re if?sys.version_info?<?(2,5):import?lxml.etree?as?ET else:import?xml.etree.ElementTree?as?ET #Define?variables template_img_path="/template/img" template_xml_path="/template/xml" vm_img_path="/var/lib/libvirt/images" vm_xml_path="/etc/libvirt/qemu" vm_file="/template/scripts/vm.ini" uri="qemu:///system" def?file_exists(file):if?os.path.exists(file):return?1else:return?0 def?copy_vm_img_file(src_img_file,dst_img_file):print?"Start?Copy",src_img_file,"to",dst_img_fileif?file_exists(dst_img_file):print?"File?%s?exists,?abort"?%?dst_img_filesys.exit(1)shutil.copyfile(src_img_file,dst_img_file)print?"Done!" def?start_vm(vm_xml_file,vm_name):try:?conn?=?libvirt.open(uri)except?Exception,e:print?'Faild?to?open?connection?to?the?hypervisor'sys.exit(1)create?=?Trueif?create:xmlfile=open(vm_xml_file)xmldesc=xmlfile.read()xmlfile.close()try:vmname?=?conn.defineXML(xmldesc)except?Exception,e:print?"Failed?to?define?%s:%s"?%(vm_name,e)sys.exit(1)if?vmname?is?None:print?'whoops?this?shouldnt?happen!'try:vmname.create()except?Exception,e:print?"Failed?to?create?%s:%s"?%(vm_name,e)sys.exit(1)try:print?"Domain?0:id?%d?running?%s"?%(vmname.ID(),vmname.name())except?Exception,e:print?etry:conn.close()except:print?"Faild?to?close?the?connection!"sys.exit(1)print?"Done!"print?"="*100 def?create_vm_xml_file(src_xml_file,vm_name,dst_img_file):config?=?ET.parse(src_xml_file)name?=?config.find('name')name.text?=?vm_name.strip()uuid?=?config.find('uuid')uuid.text?=?uuidToString(randomUUID())mac?=?config.find('devices/interface/mac')mac.attrib['address']?=?randomMAC(type='qemu')disk?=?config.find('devices/disk/source')disk.attrib['file']=dst_img_filevm_xml_name=vm_name.strip()?+?'.xml'vm_xml_file=os.path.join(vm_xml_path,vm_xml_name)if?file_exists(vm_xml_file):print?"File?%s?exists,?abort"?%?vm_xml_filesys.exit(1)config.write(vm_xml_file)print?"Created?vm?config?file?%s"?%?vm_xml_file#print?"Use?disk?image?%s,?you?must?create?it?from?the?template?disk:?%s"?%?(disk_image,?disk_old)print?"Done!"#Function?2?Start?VMprint?"Start?VM"start_vm(vm_xml_file,vm_name) def?delete_file(file_name):if?file_exists(file_name):os.unlink(file_name) def?delete_vm(vm_name):vmimg=vm_name+".img"vmxml=vm_name+".xml"img_file=os.path.join(vm_img_path,vmimg)xml_file=os.path.join(vm_xml_path,vmxml)try:conn?=?libvirt.open(uri)except?Exception,e:print?'Faild?to?open?connection?to?the?hypervisor'sys.exit(1)try:server=conn.lookupByName(vm_name)except?Exception,e:print?esys.exit(1)if?server.isActive():print?"VM?%s?will?be?shutdown!"?%vm_nametry:#server.shutdown()#VM?need?install?acpidserver.destroy()except?Exception,e:print?esys.exit(1)print?"VM?%s?will?be?delete!"?%vm_nametry:server.undefine()except?Exception,e:print?esys.exit(1)delete_file(img_file)delete_file(xml_file)try:conn.close()except:print?"Faild?to?close?the?connection!"sys.exit(1)else:print?"VM?%s?will?be?delete!"?%vm_nametry:server.undefine()except?Exception,e:print?esys.exit(1)delete_file(img_file)delete_file(xml_file)print?"Done"print?"="*100 #Open?config?file fh=open(vm_file) vm_config=fh.readlines() fh.close() for?line?in?vm_config:passline=re.compile("#.*")if?re.search(passline,line)!=None:continue(action,vm_name,src_file,xml_file)=line.strip().split(",")if?action=='add':src_img_file=os.path.join(template_img_path,src_file)dst_img_file=os.path.join(vm_img_path,vm_name.strip()+".img")src_xml_file=os.path.join(template_xml_path,xml_file)if?not?(file_exists(src_img_file)?and?file_exists(src_xml_file)):print?"File?%s?or?%s?not?exists,abort!"?%(src_img_file,src_xml_file)sys.exit(1)#Function1.1?Copy?VM?img?fileprint?"Copy?Template?VM?image?file"copy_vm_img_file(src_img_file,dst_img_file)#Function1.2?Create?VM?XML?fileprint?"Create?VM?Xml?file"create_vm_xml_file(src_xml_file,vm_name,dst_img_file)elif?action=="delete":#Function3?Delete?VMprint?"Delete?VM"delete_vm(vm_name)后期,將提供通過腳本修改些虛擬機配置的腳本.先寫這些吧.
如果想了解更多,請關注我們的公眾號
公眾號ID:opdevos
掃碼關注
總結
以上是生活随笔為你收集整理的KVM脚本批量添加删除虚拟机的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 四元玉鉴是什么朝代的
- 下一篇: struts国际化