具体可查阅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')