KVM Script Bulk Add delete virtual machine version 2

Source: Internet
Author: User

On the basis of the original, do some functional additions.

    1. To modify the host name of a virtual machine

    2. Modifying a virtual machine's Mac

    3. Modifying the IP of a virtual machine

    4. Virtual machines in qcow2 format, using Qemu-img's backing_file technology to quickly generate virtual machines

This allows the virtual machine to be managed remotely when it is created.


For the 1th edition, please refer to:

http://5ydycm.blog.51cto.com/115934/1211630


2nd edition, create_delete_vm.py code:

#!/usr/bin/env python#coding:utf-8#################################################################### Auth:zhuzhengjun#lastmodified:2015/01/14#version 1.0#function description: #Batch  automatically  generated/delete vm#1.generated vm# #1.1.create qcow2 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.edit vm# #2.1.edit hostname# #2.2.Edit Mac# #2.3. edit ip#3.start vm#4.delete vm################################################################# # # # #import  moduleimport shutilimport os,sysfrom virtinst.util import *import  libvirtimport reimport subprocessimport guestfsimport jinja2if sys.version_info  <  (2,5):        import lxml.etree as  Etelse:    &nBsp;   import xml.etree.elementtree as et#define variablestemplate_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 "domain=". tc.com "JINJA&NBSP;=&NBSP;JINJA2. Environment (&NBSP;&NBSP;&NBSP;&NBSP;LOADER=JINJA2. Filesystemloader (         '/template/jinja '     )) Def file_exists (file):     if os.path.exists (file):         return 1    else:         Return 0def create_vm_img_file (src_img_file,dst_img_file):     command= "/usr/bin/ Qemu-img create -f qcow2 -o cluster_size=2m,backing_file= "+src_img_file+"   "+dst_ Img_file+ " 20g"     try:     &nbsP;  subprocess.check_call (command,shell=true)     except subprocess. calledprocesserror as err:        print  "Error:", err         sys.exit (1)     print  "done!" Def copy_vm_img_file (src_img_file,dst_img_file):    print  "Start Copy", src_ Img_file, "to", Dst_img_file    if file_exists (dst_img_file):         print  "File %s exists, abort"  % dst_img_file         sys.exit (1)     shutil.copyfile (src_img_file,dst_img_ File)     print  "done!" DEF&NBSP;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  = True    if 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 e    try:         conn.close ()     except:        print  " faild to close the connection! "         sys.exit (1)     print  "done!"     print  "=" *100DEF&NBSP;EDIT_VM (dst_img_file,vm_mac,vm_ip,hostname): &NBsp;   g = guestfs. Guestfs (python_return_dict=true)     g.add_drive_opts (dst_img_file)      G.launch ()     partions_root=g.inspect_os ()     g.mount (partions_root[0] , '/')      #edit  hostname    hostname_fn= ' Hostname.jinja '      try:        template_hostname = jinja.get_ Template (HOSTNAME_FN)     except jinja2.exceptions.TemplateNotFound:         print  "Error"         sys.exit (1)     hostname_context={' hostname ': hostname}    hostname_content= Template_hostname.render (**hostname_context)     g.write ('/etc/sysconfig/network ', hostname_ Content)      #edit  mac    mac_fn= ' Mac.jinja ' &NBsp;   try:        template_mac = jinja.get_ Template (MAC_FN)     except jinja2.exceptions.TemplateNotFound:         print  "Error"         sys.exit (1)     mac_context={' mac ': Vm_mac}    mac_content=template_mac.render (* * Mac_context)     g.write ('/etc/udev/rules.d/70-persistent-net.rules ', mac_content)       #edit  ip    net_fn= ' Net.jinja '     try:         template_net = jinja.get_template (NET_FN)      except jinja2.exceptions.TemplateNotFound:         print  "Error"         sys.exit (1)     net_ context={' mac ': Vm_mac, ' IP ': VM_IP}&NBSP;&NBsp;  net_content=template_net.render (**net_context)     g.write ('/etc/sysconfig/ Network-scripts/ifcfg-eth0 ', net_content)     g.close () Def create_vm_xml_file (src_xml_ File,vm_name,dst_img_file,vm_ip,hostname):     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 ')     vm_mac=randommac (type= ' qemu ')     mac.attrib[' address '] =  vm_mac    disk = config.find (' Devices/disk/source ')      disk.attrib[' file ']=dst_img_file    vm_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 _file        sys.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 &NBSP;2&NBSP;EDIT&NBSP;VM&NBSP;&NBSP;&NBSP;&NBSP;EDIT_VM (Dst_img_file,vm_mac, Vm_ip,hostname)      #Function  3 Start VM    print  " start vm  "+HOSTNAME&NBSP;&NBSP;&NBSP;&NBSP;START_VM (vm_xml_file,vm_name) Def delete_File (file_name):     if file_exists (file_name):         os.unlink (file_name) DEF&NBSP;DELETE_VM (vm_name):     vmimg=vm_name+ ". Qcow2"     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 e         Sys.exit (1)     if server.isactive ():         print  "vm %s will be shutdown!"  %vm_name        try:              #server. Shutdown () #VM  need install acpid             server.destroy ()          except exception,e:            print  e            sys.exit (1)          print  "vm %s will be delete!"  %vm_name        try:             server.undefine ()         except&nbsP exception,e:            print e             sys.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_name        try:             server.undefine ()         except  exception,e:            print e             sys.exit (1)                                                   delete_file (Img_file)         delete_file (xml_file)     print  "Done"      print  "=" *100############## #Main ############################################ #Open &NBSP;CONFIG&NBSP;FILEFH =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,VM_IP) = Line.strip (). Split (",")     hostname=vm_name+domain    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 () + ". Qcow2" )         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 create qcow2 vm img file         print  "create vm " +hostname+ " image file and  File type qcow2 "        create_vm_img_file (src_img_file,dst_ Img_file)          #Function1.2 create vm xml file        print  "create vm " +hostname+ "  Xml  config file "        create_vm_xml_file (src_xml_file,vm_name , dst_img_file,vm_ip,hostname)     elif action== "Delete":          #Function4  Delete VM        print  " DELETE&NBSP;VM "&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;DELETE_VM (vm_name)

Configuration files for virtual machines:

Vm.ini

#Action, Vm_name,template_img_file,template_xml_file,vm_ipadd,web20,template_centos63x64.img,template_ Centos63x64.xml,192.168.x.26add,web30,template_centos63x64.img,template_centos63x64.xml,192.168.x.27#delete, Web20,none,none,none#delete,web30,none,none,none

Jinja Related configuration Files

Hostname.jinja hostname={{hostname}}networking=yes# ipv4networking=yesnozeroconf=yes# ipv6,  necessary for bondingNETWORKING_IPV6=yesIPV6INIT=yesmac.jinja # This file  Was automatically generated by the /lib/udev/write_net_rules# program, run  by the persistent-net-generator.rules rules file.## you can modify  it, as long as you keep each rule on a single#  line, and change only the value of the name= key.# pci  device 0x1af4:0x1000  (VIRTIO-PCI) #context ={' macs ': {' eth0 ':  {' mac ':  ' mac0 '},  ' eth1 ':  {' mac ':  ' MAC1 '}}} subsystem== "net",  action== "Add",  drivers== "? *",  attr{address} = = "{{mac}}",  attr{type}== "1",  kernel== "eth*",  name= "eth0" net.jinja device= "eth0" bootproto= "Static" Hwaddr={{mac}}Ipaddr={{ip}}netmask=255.255.255.0gateway=192.168.x.254nm_controlled= "yes" onboot= "yes" TYPE= "Ethernet" 

Batch generation is as follows:

[email protected] scripts]# python create_delete_vm.py
Create VM web20.tc.com image file and file type Qcow2
Formatting '/var/lib/libvirt/images/web20.qcow2 ', fmt=qcow2 size=21474836480 backing_file= '/template/img/Template_ Centos63x64.img ' Encryption=off cluster_size=2097152
done!
Create VM web20.tc.com Xml config file
Created VM config File/etc/libvirt/qemu/web20.xml
done!
Start VM web20.tc.com
Domain 0:id Running Web20
done!
====================================================================================================
Create VM web30.tc.com image file and file type Qcow2
Formatting '/var/lib/libvirt/images/web30.qcow2 ', fmt=qcow2 size=21474836480 backing_file= '/template/img/Template_ Centos63x64.img ' Encryption=off cluster_size=2097152
done!
Create VM web30.tc.com Xml config file
Created VM config File/etc/libvirt/qemu/web30.xml
done!
Start VM web30.tc.com
Domain 0:id Running Web30
done!
====================================================================================================

For reference!

This article is from the "Bad Boy" blog, make sure to keep this source http://5ydycm.blog.51cto.com/115934/1603999

KVM Script Bulk Add delete virtual machine version 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.