设为首页 收藏本站
查看: 2951|回复: 6

[经验分享] KVM脚本批量添加删除虚拟机

[复制链接]

尚未签到

发表于 2013-5-28 09:02:40 | 显示全部楼层 |阅读模式

[背景]最近事情特别多,前段时间搞搞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



[Shell] 纯文本查看 复制代码
<!--
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>
[iyunv@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

[iyunv@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


执行脚本,结果:

223606462.jpg

223606956.jpg

[提供代码]



[Shell] 纯文本查看 复制代码
#!/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 1
    else:
        return 0
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 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 "="*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_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 2 Start VM
    print "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 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 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
#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 file
        print "Copy Template VM image file"
        copy_vm_img_file(src_img_file,dst_img_file)
        #Function1.2 Create VM XML file
        print "Create VM Xml file"
        create_vm_xml_file(src_xml_file,vm_name,dst_img_file)
    elif action=="delete":
        #Function3 Delete VM
        print "Delete VM"
        delete_vm(vm_name)

后期,将提供通过脚本修改些虚拟机配置的脚本.先写这些吧.




运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-6174-1-1.html 上篇帖子: Linux KVM总结 下篇帖子: Linux下为KVM 配置桥接设备 虚拟机

尚未签到

发表于 2013-5-28 09:54:06 | 显示全部楼层
商女不知亡国恨、妓女不懂婚外情。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

尚未签到

发表于 2013-5-28 13:20:45 | 显示全部楼层
恐龙说:“遇到色狼,不慌不忙;遇到禽兽,慢慢享受……”

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

尚未签到

发表于 2013-5-28 13:26:34 | 显示全部楼层
关羽五绺长髯,风度翩翩,手提青龙偃月刀,江湖人送绰号——刀郎。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

尚未签到

发表于 2013-5-28 13:35:02 | 显示全部楼层
美女未抱身先走,常使色狼泪满襟。。。。。。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

发表于 2013-5-28 14:35:25 | 显示全部楼层
睡眠是一门艺术——谁也无法阻挡我追求艺术的脚步!

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

尚未签到

发表于 2013-5-28 14:42:11 | 显示全部楼层
男人有冲动可能是爱你,也可能是不爱,但没有冲动肯定是不爱!

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表