vmware克隆虚拟机并设置网络(vcenter6或5.5)

Wesley13
• 阅读 476
具体可查阅api文档https://vdc-download.vmware.com/vmwb-repository/dcr-public/6b586ed2-655c-49d9-9029-bc416323cb22/fa0b429a-a695-4c11-b7d2-2cbc284049dc/doc/index.html# coding: utf-8
import sys
import ssl
import requests
import traceback
import urllib
import json


Result = ''


def derypt_passwd(data):
    master = os.getenv('ANT_BASEURL').strip()
    url = "{}/daemon/api/v2/encryption/decrypt?encrypted_text={}".format(master.rstrip('/'), urllib.quote(data))
    res = requests.get(url)
    return res.content


class CheckError(Exception):
    pass


class CloneError(Exception):
    pass


try:
    from pyVmomi import vim
    from pyVim.connect import SmartConnect, Disconnect
    import atexit
except ImportError:
    Result = '执行主机上不存在pyVmomi,无法进行后续操作'
    print Result
    sys.exit(1)


def wait_for_task(task):
    """ wait for a vCenter task to finish """
    global Result
    task_done = False
    while not task_done:
        if task.info.state == 'success':
            return task.info.result
        if task.info.state == 'error':
            raise CloneError(task.info.error)


def get_obj(content, vimtype, name):
    """
    根据name返回对象。
    如果name为空,则返回发现的第一个值;若无任何值,返回None
    """
    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for v in container.view:
        if name:
            if v.name == name:
                obj = v
                break
        else:
            obj = v
            break
    return obj

def get_vcenter_info(vcenter):
    vcenter = json.loads(vcenter)[0]
    print vcenter
    host = vcenter['ip']
    port = int(vcenter['discoveryPort'])
    user = vcenter['username']
    password = vcenter['password']
    if '>>>' in password:
        password = derypt_passwd(password)
    virtual_datacenter = vcenter['name']
    return user, password, host, port, virtual_datacenter

def get_value(data, key=None):
    if data and data not in ('[{}]'):
        data = json.loads(data)
        if isinstance(data, str):
            return data
        elif isinstance(data[0], dict):
            if key:
                return data[0][key]
            for k, v in data[0].items():
                return v

def clone_vm(content, template, vm_name,
             datacenter_name=None, vm_folder=None, datastore_name=None,
             cluster_name=None, resource_pool_name=None, power_on=True,
             vm_ip=None, vm_subnetmask=None, vm_gateway=None, vm_domain=None,
             vm_hostname=None):
    """
    从模板/虚拟机来克隆虚拟机。
    数据中心名称,目标虚拟机文件夹,数据存储名称,
    集群名称,资源池,是否自动开机均为可选项
    """
    datacenter = get_obj(content, [vim.Datacenter], datacenter_name)

    if vm_folder:
        destfolder = get_obj(content, [vim.Folder], vm_folder)
        if not destfolder:
            raise CheckError('虚拟机目录:{}不存在'.format(vm_folder))
    else:
        destfolder = datacenter.vmFolder
        if not destfolder:
            raise CheckError('默认虚拟机目录为空')

    if datastore_name:
        datastore = get_obj(content, [vim.Datastore], datastore_name)
        if not datastore:
            raise CheckError('数据存储:{}不存在'.format(datastore_name))
    else:
        datastore = get_obj(
            content, [vim.Datastore], template.datastore[0].info.name)
        if not datastore:
            raise CheckError('默认数据存储为空')

    if resource_pool_name:
        resource_pool = get_obj(content, [vim.ResourcePool], resource_pool_name)
        if not resource_pool:
            raise CheckError('资源池:{}不存在'.format(resource_pool_name))
    else:
        cluster = get_obj(content, [vim.ClusterComputeResource], cluster_name)
        if cluster:
            resource_pool = cluster.resourcePool
        else:
            resource_pool = get_obj(content, [vim.ResourcePool], None)
        if not resource_pool:
            raise CheckError('默认资源池为空')

    relospec = vim.vm.RelocateSpec()
    relospec.datastore = datastore
    relospec.pool = resource_pool

    clonespec = vim.vm.CloneSpec()
    clonespec.location = relospec
    clonespec.powerOn = power_on
    if all([vm_ip, vm_subnetmask, vm_gateway, vm_domain]):
        clonespec.customization = get_customspec(vm_ip, vm_subnetmask, vm_gateway, vm_domain, vm_hostname)
    elif any([vm_ip, vm_subnetmask, vm_gateway, vm_domain]):
        raise CheckError('虚拟机的IP、子网掩码、网关、DNS域必须同时提供')

    print '开始克隆虚拟机'
    task = template.Clone(folder=destfolder, name=vm_name, spec=clonespec)
    wait_for_task(task)


def get_customspec(vm_ip=None, vm_subnetmask=None, vm_gateway=None,
                   vm_domain=None, vm_hostname=None):
    # guest NIC settings
    adaptermaps = []
    guest_map = vim.vm.customization.AdapterMapping()
    guest_map.adapter = vim.vm.customization.IPSettings()
    guest_map.adapter.ip = vim.vm.customization.FixedIp()
    guest_map.adapter.ip.ipAddress = vm_ip
    guest_map.adapter.subnetMask = vm_subnetmask
    guest_map.adapter.gateway = vm_gateway
    guest_map.adapter.dnsDomain = vm_domain
    adaptermaps.append(guest_map)

    # DNS settings
    globalip = vim.vm.customization.GlobalIPSettings()
    globalip.dnsServerList = [vm_gateway]
    globalip.dnsSuffixList = vm_domain

    # Hostname settings
    ident = vim.vm.customization.LinuxPrep()
    ident.domain = vm_domain
    ident.hostName = vim.vm.customization.FixedName()
    if vm_hostname:
        ident.hostName.name=vm_hostname
        #ident.hostName.name = vm_hostname
    customspec = vim.vm.customization.Specification()
    customspec.nicSettingMap = adaptermaps
    customspec.globalIPSettings = globalip
    customspec.identity = ident
    return customspec


if __name__ == '__main__':
    try:
        ssl._create_default_https_context = ssl._create_unverified_context
        requests.packages.urllib3.disable_warnings()

        print cluster_name, template_name, vm_folder, datastore_name, resource_pool, vCenter
        cluster_name = get_value(cluster_name, key='name')
        template_name = get_value(template_name, key='name')
        vm_folder = get_value(vm_folder, key='name')

        datastore_name = get_value(datastore_name, key='name')
        resource_pool = get_value(resource_pool, key='name')

        print cluster_name, template_name, vm_folder, datastore_name, resource_pool

        power_on = True if power_on == 'true' else False
        cpu_num = int(cpu_num) if cpu_num else None
        memory = int(memory) if memory else None

        user, passwd, host, port, virtual_datacenter_name = get_vcenter_info(vCenter)

        print user, passwd, host, port, virtual_datacenter_name

        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        si = SmartConnect(host=host,
                          user=user,
                          pwd=passwd,
                          port=port,
                          sslContext=context)
        atexit.register(Disconnect, si)


        content = si.RetrieveContent()
        template = get_obj(content, [vim.VirtualMachine], template_name)
        vm_hostname=vm_name.replace('_','')
        vm_folder=''
        if template:
            clone_vm(content, template, vm_name,
                     virtual_datacenter_name, vm_folder, datastore_name,
                     cluster_name, resource_pool, power_on,
                     vm_ip, vm_subnet_mask, vm_gateway,
                     vm_domain,  vm_hostname)
        else:
            raise CheckError('模板:{}不存在'.format(template_name))
        Result = '克隆虚拟机成功'
        print Result
        sys.exit(0)
    except Exception as e:
        print e
        print traceback.format_exc()
        Result = '克隆虚拟机失败'
        print Result
        sys.exit(1)

  获取虚拟机信息

import ssl
import pysphere
import json
from pysphere import VIServer,MORTypes,VIProperty
from pysphere.resources import VimService_services as VI

def derypt_passwd(data):
    master = os.getenv('ANT_BASEURL').strip()
    url = "{}/daemon/api/v2/encryption/decrypt?encrypted_text={}".format(master.rstrip('/'), urllib.quote(data))
    res = requests.get(url)
    return res.content


def get_vcenter_info(vcenter):
    vcenter = json.loads(vcenter)[0]
    #print vcenter
    host = vcenter['ip']
    port = int(vcenter['discoveryPort'])
    user = vcenter['username']
    password = vcenter['password']
    if '>>>' in password:
        password = derypt_passwd(password)
    virtual_datacenter = vcenter['name']
    return user, password, host, port, virtual_datacenter

        
ssl._create_default_https_context = ssl._create_unverified_context
user, passwd, host, port, virtual_datacenter_name = get_vcenter_info(vCenter)

s = VIServer()
s.connect(host,user,passwd)

vm1 = s.get_vm_by_name(vm_name)
vm_info = vm1.get_properties()
print vm_info
ip_address = vm_info.get('ip_address')
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这