本文整理汇总了Python中pysphere.VIServer._retrieve_properties_traversal方法的典型用法代码示例。如果您正苦于以下问题:Python VIServer._retrieve_properties_traversal方法的具体用法?Python VIServer._retrieve_properties_traversal怎么用?Python VIServer._retrieve_properties_traversal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pysphere.VIServer
的用法示例。
在下文中一共展示了VIServer._retrieve_properties_traversal方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: retrieve
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
def retrieve(self, request, *args, **kwargs):
host_ip_r = kwargs['host_ip']
try:
host_serializer = serializers.VMwareHostSerializer(self.queryset.get(host_ip=host_ip_r))
instances_set = models.VMwareInstance.objects.filter(host_ip=host_serializer.data['host_ip'])
instances_count = instances_set.count()
mem_used = 0
vcpus = 0
ecu = 0
for instance in instances_set:
mem_used += int(instance.mem[0:len(instance.mem)-2])
a = int(instance.cpu[0:instance.cpu.find("vcpu")])
vcpus += a
ecu += int(instance.cpu[instance.cpu.find("ecu")-1:instance.cpu.find("ecu")]) * a
host_serializer.data['memory_used'] = str(mem_used/1024) + "GB"
host_serializer.data['vcpus_used'] = vcpus
host_serializer.data['ecus_used'] = ecu
host_serializer.data['instances_count'] = instances_count
server = VIServer()
server.connect(host_serializer.data['host_ip'], 'root', '[email protected]')
properties = ['capability.maxSupportedVMs',
'capability.maxSupportedVcpus',
'runtime.bootTime',
'runtime.powerState',
'summary.config.product.osType',
'summary.config.product.fullName',
'summary.config.product.licenseProductVersion',
'summary.config.product.licenseProductName',
'summary.config.product.instanceUuid',
'hardware.cpuPowerManagementInfo.hardwareSupport']
results = server._retrieve_properties_traversal(property_names=properties, obj_type=MORTypes.HostSystem)
for result in results:
for p in result.PropSet:
if p.Name == 'hardware.cpuInfo.hz':
value = str(p.Val/(1024*1024*1024)) + " GHz"
elif p.Name == 'hardware.memorySize':
value = str(p.Val/(1024*1024)) + " MB"
elif p.Name == 'config.certificate':
value = str(p.Val)
elif p.Name == 'runtime.bootTime':
value = str(p.Val[0]) + "-" + str(p.Val[1]) + "-" + str(p.Val[2]) + " "
value = value + str(p.Val[3]) + ":" + str(p.Val[4])
else:
value = str(p.Val)
name = p.Name.split('.')[-1]
host_serializer.data[name] = value
return Response(host_serializer.data)
except VMwareHost.DoesNotExist:
raise Http404
示例2: CheckVCenter
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
class CheckVCenter():
def __init__(self):
self.server = VIServer()
self.STAT_OK=0
self.STAT_WARNING=1
self.STAT_CRITICAL=2
self.vc = sys.argv[1]
self.user = sys.argv[2]
self.password = sys.argv[3]
@staticmethod
def PrintDict(i,status):
for k,v in i.items():
print "VMFS %s lun:%s -----*----*---- usage:%d%%" %(status,k,v)
def Check(self):
self.server.connect(self.vc,self.user,self.password)
Value = self.server.get_datastores()
c = {}
w = {}
n = {}
for k,v in Value.items():
props = self.server._retrieve_properties_traversal(property_names=['name','summary.capacity',
'summary.freeSpace'],
from_node=k,obj_type='Datastore')
for p_set in props:
for p1 in p_set.PropSet:
if p1.Name == "summary.capacity":
DatastoreCapacity = (p1.Val/1073741824)
elif p1.Name == "summary.freeSpace":
DatastoreFreespace = (p1.Val/1073741824)
Percent = (((DatastoreCapacity - DatastoreFreespace) * 100)/DatastoreCapacity)
if Percent > 90 and 'ISO' not in v:
c[v] = Percent
elif Percent > 85 < 90 and 'ISO' not in v:
w[v] = Percent
elif Percent < 85 and 'ISO' not in v:
n[v] = Percent
if dict(c):
CheckVCenter.PrintDict(c,'CRITICAL')
sys.exit(self.STAT_CRITICAL)
elif dict(w):
CheckVCenter.PrintDict(w,'WARNING')
sys.exit(self.STAT_WARNING)
else:
print("All Lun is OK")
sys.exit(self.STAT_OK)
示例3: vi_retrieve_host_objects
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
def vi_retrieve_host_objects(host,properties):
s = VIServer()
s.connect(vi_configuration["VI_HOST"], vi_configuration["VI_USER"], vi_configuration["VI_PASS"])
# If we can't find this host in the get_hosts() output then it doesn't exist
# on this vCenter. We catch this with an indexError and return false to be
# detected upstream. Can we do this quicker? Takes ~2s to retrieve the hosts
# on a loaded 4.1 vCenter.
try:
from_host = [k for k,v in s.get_hosts().items() if v == host][0]
result = s._retrieve_properties_traversal(property_names=properties,from_node=from_host,obj_type=MORTypes.HostSystem)[0]
except IndexError:
result = False
s.disconnect()
return result
示例4: info
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
def info(self, request, host_ip):
try:
instance_name = request.GET.get('ins_name') or None
if instance_name is None:
content = {'Error!': 'Instance name is None,You must specify instance name'}
return Response(content)
else:
instance_serializer = serializers.VMwareInstanceSerializer(self.queryset.get(instance_name=instance_name))
uptime = instance_serializer.data['up_time']
if uptime.strip() == '':
time_str = " "
else:
time_str = change_time_format(int(uptime))
instance_serializer.data['up_time'] = time_str
server = VIServer()
server.connect(host_ip, 'root', '[email protected]')
properties = ['name', 'runtime.maxCpuUsage', 'runtime.maxMemoryUsage', 'summary.config.vmPathName',
'runtime.suspendInterval', 'config.instanceUuid', 'config.locationId',
'summary.config.cpuReservation', 'config.guestFullName', 'config.version',
'guest.guestState', 'guest.hostName', 'guest.ipAddress', 'runtime.bootTime',
'runtime.connectionState']
results = server._retrieve_properties_traversal(property_names=properties, obj_type=MORTypes.VirtualMachine)
for result in results:
for p in result.PropSet:
if p.Name == 'name' and p.Val != instance_name:
break
pname = p.Name.split('.')[-1]
if p.Name != 'name':
pvalue = p.Val
instance_serializer.data[pname] = pvalue
if p.Name == 'runtime.bootTime':
v = p.Val
pvalue = str(v[0]) + '-' + str(v[1]) + '-' + str(v[2]) + ' ' + str(v[3]) + ':' + str(v[4])
instance_serializer.data[pname] = pvalue
return Response(instance_serializer.data)
except VMwareInstance.DoesNotExist:
raise Http404
示例5: VMWareSystem
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
class VMWareSystem(MgmtSystemAPIBase):
"""Client to Vsphere API
This class piggy backs off pysphere.
Benefits of pysphere:
- Don't need intimate knowledge w/ vsphere api itself.
Detriments of pysphere:
- Response often are not detailed enough.
"""
_stats_available = {
'num_vm': lambda self: len(self.list_vm()),
'num_host': lambda self: len(self.list_host()),
'num_cluster': lambda self: len(self.list_cluster()),
'num_template': lambda self: len(self.list_template()),
'num_datastore': lambda self: len(self.list_datastore()),
}
def __init__(self, hostname, username, password, **kwargs):
self.api = VIServer()
self.api.connect(hostname, username, password)
def _get_vm(self, vm_name=None):
if vm_name is None:
raise Exception('Could not find a VM named %s.' % vm_name)
else:
try:
vm = self.api.get_vm_by_name(vm_name)
return vm
except VIException as ex:
raise Exception(ex)
def does_vm_exist(self, name):
try:
self._get_vm(name)
return True
except Exception:
return False
def _get_resource_pool(self, resource_pool_name=None):
rps = self.api.get_resource_pools()
for mor, path in rps.iteritems():
if re.match('.*%s' % resource_pool_name, path):
return mor
# Just pick the first
return rps.keys()[0]
def get_ip_address(self, vm_name):
vm = self._get_vm(vm_name)
maxwait = 600
net_info = None
waitcount = 0
while net_info is None:
if waitcount > maxwait:
break
net_info = vm.get_property('net', False)
waitcount += 5
time.sleep(5)
if net_info:
ipv4_re = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
for ip in net_info[0]['ip_addresses']:
if re.match(ipv4_re, ip) and ip != '127.0.0.1':
return ip
return None
def _get_list_vms(self, get_template=False):
template_or_vm_list = []
props = self.api._retrieve_properties_traversal(property_names=['name', 'config.template'],
from_node=None,
obj_type=MORTypes.VirtualMachine)
for prop in props:
vm = None
template = None
for elem in prop.PropSet:
if elem.Name == "name":
vm = elem.Val
elif elem.Name == "config.template":
template = elem.Val
if vm is None or template is None:
continue
if template == bool(get_template):
template_or_vm_list.append(vm)
return template_or_vm_list
def start_vm(self, vm_name):
vm = self._get_vm(vm_name)
if vm.is_powered_on():
return True
else:
vm.power_on()
ack = vm.get_status()
if ack == 'POWERED ON':
return True
return False
def stop_vm(self, vm_name):
vm = self._get_vm(vm_name)
#.........这里部分代码省略.........
示例6: get_stats
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
def get_stats():
stats = dict()
v = VCENTERLIST.split()
for vcenter in v:
logger('verb', "get_stats calls vcenter %s user %s" % (vcenter, USERNAME))
server = VIServer()
try:
server.connect(vcenter, USERNAME, PASSWORD)
except Exception:
logger('warn', "failed to connect to %s" % (vcenter))
continue
# get datastores
for ds, dsname in server.get_datastores().items():
DatastoreCapacity = 0
DatastoreFreespace = 0
DatastoreUsagePercent = 0
try:
logger('verb', "get_stats calls Datastore metrics query on vcenter: %s for datastore: %s" % (vcenter, dsname))
props = server._retrieve_properties_traversal(property_names=['name', 'summary.capacity', 'summary.freeSpace'], from_node=ds, obj_type="Datastore")
for prop_set in props:
# mor = prop_set.Obj #in case you need it
for prop in prop_set.PropSet:
if prop.Name == "summary.capacity":
DatastoreCapacity = (prop.Val / 1048576)
elif prop.Name == "summary.freeSpace":
DatastoreFreespace = (prop.Val / 1048576)
except Exception:
logger('warn', "failed to get Datastore metrics value on vcenter: %s for datastore: %s" % (vcenter, dsname))
DatastoreUsagePercent = (((DatastoreCapacity - DatastoreFreespace) * 100) / DatastoreCapacity)
metricnameZoneDatastoreCapacity = METRIC_DELIM.join([vcenter.lower(), "datastores", dsname.lower(), 'datastorecapacity'])
metricnameZoneDatastoreFreespace = METRIC_DELIM.join([vcenter.lower(), "datastores", dsname.lower(), 'datastorefreespace'])
metricnameZoneDatastoreUsagePercent = METRIC_DELIM.join([vcenter.lower(), "datastores", dsname.lower(), 'datastoreusagepercent'])
try:
stats[metricnameZoneDatastoreCapacity] = DatastoreCapacity
stats[metricnameZoneDatastoreFreespace] = DatastoreFreespace
stats[metricnameZoneDatastoreUsagePercent] = DatastoreUsagePercent
except (TypeError, ValueError):
pass
ZoneDatacentersCount = 0
ZoneClustersCount = 0
ZoneHostsCount = 0
ZoneRunningVMS = 0
ZoneStoppedVMS = 0
ZoneTotalVMS = 0
ZoneMemoryUsage = 0
ZoneCpuUsage = 0
ZoneTotalMemory = 0
ZoneCpuTotal = 0
logger('verb', "get_stats calls get_datacenters query on vcenter: %s" % (vcenter))
datacenters = server.get_datacenters()
logger('verb', "get_stats completed get_datacenters query on vcenter: %s" % (vcenter))
ZoneDatacentersCount = len(datacenters)
for d, dname in server.get_datacenters().items():
if "." in dname:
dname = dname.split(".")[0]
DatacenterRunningVMS = 0
DatacenterStoppedVMS = 0
DatacenterTotalVMS = 0
DatacenterClustersCount = 0
DatacenterHostsCount = 0
DatacenterMemoryUsage = 0
DatacenterCpuUsage = 0
DatacenterTotalMemory = 0
DatacenterCpuTotal = 0
logger('verb', "get_stats calls get_clusters query on vcenter: %s for datacenter: %s" % (vcenter, dname))
clusters = server.get_clusters(d)
logger('verb', "get_stats completed get_clusters query on vcenter: %s for datacenter: %s" % (vcenter, dname))
DatacenterClustersCount = len(clusters)
ZoneClustersCount = ZoneClustersCount + DatacenterClustersCount
for c, cname in server.get_clusters(d).items():
if "." in cname:
cname = cname.split(".")[0]
ClusterMemoryUsage = 0
ClusterCpuUsage = 0
ClusterTotalMemory = 0
ClusterCpuTotal = 0
ClusterRunningVMS = 0
ClusterStoppedVMS = 0
ClusterTotalVMS = 0
#.........这里部分代码省略.........
示例7:
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
except Exception:
print "CRITICAL - Unable to connect to vSphere"
sys.exit(2)
# collect dict of hosts
hosts = server.get_hosts()
# create an integer to track number of operational and down hosts
hosts_operational = 0
hosts_down = 0
# verify that we got information
if hosts:
# get properties
props = server._retrieve_properties_traversal(property_names=['name', 'runtime.connectionState'], obj_type="HostSystem")
# get powerState for each host
for prop_set in props:
for prop in prop_set.PropSet:
# add host to correct count based on runtime powered state
if prop.Val == "connected":
hosts_operational = hosts_operational + 1
else:
hosts_down = hosts_down + 1
else:
print "CRITICAL - Unable to retrieve hosts"
sys.exit(2)
# disconnect from vcenter
示例8: __init__
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
#.........这里部分代码省略.........
host_system = [k for k, v in hosts.items() if v == esx_hostname][0]
else:
host_system = hosts.keys()[0]
except IndexError:
raise CreatorException("Couldn't find host")
if not host_system:
raise CreatorException("Couldn't find host")
prop = VIProperty(self.esx_server, host_system)
for pg in prop.configManager.networkSystem.networkInfo.portgroup:
if pg.spec.name.lower() == name.lower():
real_name = pg.spec.name
# self._disconnect_from_esx()
return real_name
# self._disconnect_from_esx()
return None
# todo: add comment
def _is_vm_exist(self, name):
"""
:param name:
:return:
"""
self._connect_to_esx()
exist = False
try:
self.esx_server.get_vm_by_name(name)
exist = True
except:
pass
# self._disconnect_from_esx()
return exist
# todo: add comment
def _fetch_resource_pool(self, rp_name, esx_hostname):
"""
:param rp_name:
:param esx_hostname:
:return:
"""
rpmor = None
if rp_name == "/":
rp_mor_temp = [k for k, v in self.esx_server.get_resource_pools().items() if v == "/Resources"]
for rp in rp_mor_temp:
prop = VIProperty(self.esx_server, rp)
if prop.parent.name == esx_hostname:
rpmor = rp
break
else:
resource_pool = "/Resources" + rp_name
rp_mor_temp = [k for k, v in self.esx_server.get_resource_pools().items() if v == resource_pool]
for rp in rp_mor_temp:
prop = VIProperty(self.esx_server, rp)
while prop.parent.name != "host":
prop = prop.parent
if prop.name == esx_hostname:
rpmor = rp
break
if rp:
break
return rpmor
# todo: add comment
def _fetch_computer_resource(self, datacenter_props, host):
"""
:param datacenter_props:
:param host:
:return:
"""
host_folder = datacenter_props.hostFolder._obj
# get computer resources
computer_resources = self.esx_server._retrieve_properties_traversal(
property_names=["name", "host"], from_node=host_folder, obj_type="ComputeResource"
)
# get computer resource of this host
crmor = None
for cr in computer_resources:
if crmor:
break
for p in cr.PropSet:
if p.Name == "host":
for h in p.Val.get_element_ManagedObjectReference():
if h == host:
crmor = cr.Obj
break
if crmor:
break
return VIProperty(self.esx_server, crmor)
示例9: __init__
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
class Vmware:
def __init__(self):
self.host = config.vmware_host
self.user = config.vmware_user
self.pwd = config.vmware_pass
self.connection = VIServer()
self.connection.connect(self.host, self.user, self.pwd)
self.props = VIProperty(self.connection, self.connection._do_service_content.CustomFieldsManager)
self.custom_fields = dict((cf.key, cf.name) for cf in self.props.field)
def get_servers(self):
obj_type = 'HostSystem'
return self._get_initial_data(relations.vmware_server, obj_type)
def get_hypervisors(self):
obj_type = 'HostSystem'
return self._get_initial_data(relations.vmware_hypervisor, obj_type)
def get_virtual_machines(self):
obj_type = 'VirtualMachine'
return self._get_initial_data(relations.vmware_virtual_machine, obj_type)
def get_farm(self):
obj_type = 'ClusterComputeResource'
return self._get_initial_data(relations.vmware_farm, obj_type)
def get_os_versions(self):
hosts_os_versions = self._get_initial_data(relations.vmware_hosts_os_versions, 'HostSystem')
vms_os_versions = self._get_initial_data(relations.vmware_vms_os_versions, 'VirtualMachine')
os_versions = []
hosts_os_versions.extend(vms_os_versions)
for os_version in hosts_os_versions:
if len(os_version.keys()) >= 2:
if os_version not in os_versions:
os_versions.append(os_version)
return os_versions
def get_os_familys(self):
hosts_os_familys = self.get_facts('summary.config.product.name', 'HostSystem')
vms_os_familys = self.get_facts('guest.guestFamily', 'VirtualMachine')
os_familys = []
for os_family in hosts_os_familys | vms_os_familys:
os_familys.append({'name': os_family})
return os_familys
def get_brands(self):
facts_brand = self.get_facts('summary.hardware.vendor', 'HostSystem')
brands = []
for brand in facts_brand:
brands.append({'name': brand})
return brands
def get_models(self):
obj_type = 'HostSystem'
return self._get_initial_data(relations.vmware_models, obj_type)
def _get_initial_data(self, data_map, obj_type):
properties = self.connection._retrieve_properties_traversal(property_names=data_map.values(), obj_type=obj_type)
result = []
for obj in properties:
if not hasattr(obj, "PropSet"):
continue
host = {}
result.append(host)
for prop in obj.PropSet:
for key, value in data_map.iteritems():
if prop.Name == value:
if prop.Name == "summary.hardware.otherIdentifyingInfo":
for license_info in prop.Val.HostSystemIdentificationInfo:
if 'Service tag of the system' in license_info.IdentifierType.Summary:
host['serialnumber'] = license_info.IdentifierValue
elif 'Product ID:' in license_info.IdentifierValue:
host['asset_number'] = license_info.IdentifierValue.split(": ")[1]
elif prop.Name == "customValue":
for annotation in prop.Val.CustomFieldValue:
try:
host['description'] += str(self.custom_fields.get(annotation.Key)) + ": " + str(annotation.Value) + "\n"
except KeyError:
host['description'] = str(self.custom_fields.get(annotation.Key)) + ": " + str(annotation.Value) + "\n"
elif prop.Name == "summary.hardware.memorySize":
host[key] = prop.Val / (1024 * 1024)
else:
try:
host[key] = prop.Val
except SyntaxError:
host[key] = None
return result
def get_relations(self, first_fact, second_fact, obj_type):
result = {}
data_map = {'first_fact': first_fact,
'second_fact': second_fact
}
data = self._get_initial_data(data_map, obj_type)
for item in data:
#.........这里部分代码省略.........
示例10: create_vm
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
def create_vm():
opts = options()
# CONNECTION PARAMTERS
server = opts.esx_host
user = opts.user
password = opts.passwd
# REQUIRED PARAMETERS
vmname = opts.name
# datacentername = "ha-datacenter"
datacentername = opts.datacenter
hostname = opts.hostname
annotation = "My Product Product Virtual Machine"
memorysize = opts.ram
cpucount = opts.cpus
# cd_iso_location =
# "iso/My_Product_2013_02_26_05_15_00.iso"
# # located in the ESX datastore
cd_iso_location = opts.iso
guestosid = "centos64Guest"
# find your os in
# http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html
disksize = (1024 ** 2) * 100 # In Kb: 1024 ** 2 (power) = 1GB; 1GB * 100 = 100GB.
# OPTIONAL PARAMETERS
datastorename = opts.datastore # if None, will use the first datastore available
# CONNECT TO THE SERVER
s = VIServer()
s.connect(server, user, password)
# GET INITIAL PROPERTIES AND OBJECTS
# get datacenter
dcmor = s._get_datacenters()[datacentername]
dcprops = VIProperty(s, dcmor)
# get host folder
hfmor = dcprops.hostFolder._obj
# get computer resources
crmors = s._retrieve_properties_traversal(property_names=['name',
'host'], from_node=hfmor, obj_type='ComputeResource')
# get host
for hosts in s.get_hosts().items():
try:
if hosts.index(hostname) == 1:
hostmor = hosts[0]
except:
pass
# get computer resource of this host
crmor = None
for cr in crmors:
if crmor:
break
for p in cr.PropSet:
# print 'p.Name:', p.Name
if p.Name == "host":
for h in p.Val.get_element_ManagedObjectReference():
if h == hostmor:
crmor = cr.Obj
break
if crmor:
break
crprops = VIProperty(s, crmor)
# get resource pool
rpmor = crprops.resourcePool._obj
# get vmFolder
vmfmor = dcprops.vmFolder._obj
# CREATE VM CONFIGURATION
# get config target
request = VI.QueryConfigTargetRequestMsg()
_this = request.new__this(crprops.environmentBrowser._obj)
_this.set_attribute_type(crprops.environmentBrowser._obj.get_attribute_type())
request.set_element__this(_this)
h = request.new_host(hostmor)
h.set_attribute_type(hostmor.get_attribute_type())
request.set_element_host(h)
config_target = s._proxy.QueryConfigTarget(request)._returnval
# get default devices
request = VI.QueryConfigOptionRequestMsg()
_this = request.new__this(crprops.environmentBrowser._obj)
_this.set_attribute_type(crprops.environmentBrowser._obj.get_attribute_type())
request.set_element__this(_this)
h = request.new_host(hostmor)
h.set_attribute_type(hostmor.get_attribute_type())
request.set_element_host(h)
config_option = s._proxy.QueryConfigOption(request)._returnval
defaul_devs = config_option.DefaultDevice
# get network name
# would be assigned to the last known working network interface.
#.........这里部分代码省略.........
示例11: VirtualMachine_ServerList
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
def VirtualMachine_ServerList(VIServer, categories, cluster=None, status=None, tagID=201):
"""
Die Funktion hollt sich als erstes die Informationen "customValue" und "config.files.vmPathName" aka. den Pfad aller VMs aus dem Server raus.
Daraus werden nur die VMs genomen, die den Schluessel 201 aka. "Shutdown-Reihenfolge" besitzen und der mit den uebergeben Parametern uebereinstimmt.
Folgend darauf werden alle laufende VMs gelistet. Diese werden dann mit den VMs die zufor ausgefiltert worden sind abgegliechen und als eine Liste zurueck gegeben.
"""
if status and cluster:
VirtualMachineFetchResult = VIServer.get_registered_vms(cluster=cluster, status=status)
logger.info("Fetching Virtual Machines from cluster: '" + cluster + "' with the status: '" + status + "'")
elif status and cluster is None:
VirtualMachineFetchResult = VIServer.get_registered_vms(status=status)
logger.info("Fetching Virtual Machines with the status: '" + status + "'")
elif cluster and status is None:
VirtualMachineFetchResult = VIServer.get_registered_vms(cluster=cluster)
logger.info("Fetching Virtual Machines from cluster: '" + cluster + "'")
else:
VirtualMachineFetchResult = VIServer.get_registered_vms()
logger.info("Fetching all Virtual Machines from vSphere")
if categories and tagID:
logger.info(
"Filtering Virtual Machines by annotation ID: " + str(tagID) + " with the following content: " + ", ".join(
categories))
VirtualMachineList = []
VirtualMachinesWithAnnotation = []
VirtualMachinesRelated = []
ProperetyNames = ['customValue', 'config.files.vmPathName', 'config.template']
ProperetyResults = VIServer._retrieve_properties_traversal(property_names=ProperetyNames, obj_type="VirtualMachine")
for obj in ProperetyResults:
VirtualMachine = {'annotations': []}
VirtualMachineList.append(VirtualMachine)
if not hasattr(obj, "PropSet"):
continue
for prop in obj.PropSet:
if prop.Name == "name":
VirtualMachine['name'] = prop.Val
elif prop.Name == "config.files.vmPathName":
VirtualMachine['path'] = prop.Val
elif prop.Name == "config.template":
VirtualMachine['is_template'] = prop.Val
elif prop.Name == "customValue":
for annotation in prop.Val.CustomFieldValue:
VirtualMachine['annotations'].append((annotation.Key, annotation.Value))
for VirtualMachine in VirtualMachineList:
if not VirtualMachine['is_template']:
for annotation in VirtualMachine['annotations']:
if tagID in annotation:
for category in categories:
if category in annotation:
VirtualMachinesWithAnnotation.append(VirtualMachine['path'])
for i in VirtualMachinesWithAnnotation:
if i in VirtualMachineFetchResult:
VirtualMachinesRelated.append(i)
return VirtualMachinesRelated
else:
return VirtualMachineFetchResult
示例12: VIServer
# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import _retrieve_properties_traversal [as 别名]
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
from pysphere import VIServer
server = VIServer()
HOST = "172.17.11.74"
LOGIN = "root"
PASSWORD = "password"
server.connect(HOST, LOGIN, PASSWORD)
oc = []
oc.append(server._retrieve_properties_traversal(obj_type='VirtualMachine'))
power = []
machines = server.get_registered_vms()
for machine in server.get_registered_vms():
power.append(server.get_vm_by_path(machine).get_status())
zindex = -1
for elem in oc:
for b in elem:
s = (b)
zindex = zindex + 1
print "vmrc://" + LOGIN + ":" + PASSWORD + "@" + HOST + ":443/?moid=" + s.Obj, machines[zindex], power[zindex]