当前位置: 首页>>代码示例>>Python>>正文


Python VIServer.get_datacenters方法代码示例

本文整理汇总了Python中pysphere.VIServer.get_datacenters方法的典型用法代码示例。如果您正苦于以下问题:Python VIServer.get_datacenters方法的具体用法?Python VIServer.get_datacenters怎么用?Python VIServer.get_datacenters使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pysphere.VIServer的用法示例。


在下文中一共展示了VIServer.get_datacenters方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: poll_vcenter

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
    def poll_vcenter(self, vcenter):
        """
        Open a connection to the specified vCenter server and begin gathering
        information about its datastores, datacenters, clusters, and hosts.

        :param str vcenter:
            The hostname or IP of a vCenter server.

        :returns:
            A dictionary containing information about the current state of
            objects managed by the specified vCenter.

        """

        self.log.debug('polling %[email protected]%s' % (self.username, vcenter))
        server = VIServer()

        try:
            server.connect(vcenter, self.username, self.password)
        except:
            self.log.exception('Failed to connect to %s' % (vcenter,))
            return {}

        stats = {
            'datastore': {},
            'datacenter': {},
        }

        for obj, name in server.get_datastores().items():
            ds_stats = self.poll_datastore(server, obj, name)
            stats['datastore'][name] = ds_stats

        datacenters = server.get_datacenters()
        for obj, name in datacenters.items():
            dc_stats = self.poll_datacenter(server, obj, name)
            stats['datacenter'][name] = dc_stats

        return stats
开发者ID:codekoala,项目名称:collectd-vcenter,代码行数:40,代码来源:vcenter.py

示例2: hasattr

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
try:
	sock.connect( (CARBON_SERVER,CARBON_PORT) )
except:
  print "Couldn't connect to %(server)s on port %(port)d, is carbon-agent.py running?" % { 'server':CARBON_SERVER, 'port':CARBON_PORT }
  sys.exit(1)
try:
	server.connect(HOST, USER, PASSWORD)
except:
	print "Unable to connect to vsphere server"
	sys.exit(1)
pm = server.get_performance_manager()

while True:
	lines = []
	for dc_mor, dc_name in server.get_datacenters().items():
		now = int(time.time())
		datastores = server.get_datastores(dc_mor)
		for ds_mor, ds_name in datastores.items():
			gphDSName = ds_name.replace('.', '_')
			gphDSName = gphDSName.replace(' ', '_')
			props = VIProperty(server, ds_mor)
			lines.append(prefix + dc_name + ".datastores." + props.summary.type + "." + gphDSName + ".capacity " + str(props.summary.capacity) + " " + str(now))
                	lines.append(prefix + dc_name + ".datastores." + props.summary.type + "." + gphDSName + ".freespace " + str(props.summary.freeSpace) + " " +str(now))
			if hasattr(props.summary, "uncommitted"):
				lines.append(prefix + dc_name + ".datastores." + props.summary.type + "." + gphDSName + ".uncommitted " + str(props.summary.uncommitted) + " " + str(now))
	message = '\n'.join(lines) + '\n'
	sock.sendall(message)
	print message
	time.sleep(delay)
server.disconnect()
开发者ID:obazoud,项目名称:Python-Vsphere-To-Graphite,代码行数:32,代码来源:data-store-mon.py

示例3: __init__

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]

#.........这里部分代码省略.........


        :rtype: list
        :return: A list of :class:`vmware.vsphere.VM`
        
        """

        # get the vm paths
        if instanceUuid and len(instanceUuid):
            if not isinstance(instanceUuid, str):
                raise BadParameterError("instanceUuid parameter must be a string")
            if not filter:
                filter = {}
            filter["config.instanceUuid"] = [instanceUuid]

        self._vmspaths = self._server.get_registered_vms(datacenter, advanced_filters=filter)
        logger.debug("list_instances: retrieved %d vm paths" % len(self._vmspaths))
        # instantiate instances for vm paths
        self.vms = []
        for p in self._vmspaths:
            self.vms.append(VM(p, self))

        # first time this function runs, fetch information about vm to datacenter mapping
        self._fetch_datacenter_vms()
        return self.vms

    def get_hosts(self, datacenter=None):
        """Returns a dictionary of the existing hosts keys are their names
        and values their ManagedObjectReference object.
        
        Example usage:
        >>> server.get_hosts()
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219', 'host-36': '173.71.195.168'}
        >>> server.get_hosts('datacenter-12')
        >>> from catosphere import Server
        >>> server = Server()
        >>> server.connect()
        >>> server.get_datacenters()
        {'datacenter-12': 'csk3', 'datacenter-2': 'csk1', 'datacenter-7': 'csk2'}
        >>> server.get_hosts('datacenter-2')
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219'}
        >>> server.get_hosts('datacenter-7')
        {'host-36': '173.71.195.168'}
        >>> server.get_hosts('datacenter-12')
        {}
        >>> server.get_hosts()
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219', 'host-36': '173.71.195.168'}
        >>> server.disconnect()
        
        
        :return: a dict   
         e.g.
        {'host-23': '108.61.71.220', 'host-19': '108.61.71.219', 'host-36': '173.71.195.168'}
        if not hosts are found, empty dict is returned.

        """
        if datacenter:
            hosts = self._server._get_managed_objects(MORTypes.HostSystem, from_mor=datacenter)
        else:
            hosts = self._server.get_hosts()
        return hosts

    def get_datacenters(self):
        """Returns a dictionary of the existing datacenters. keys are their
        ManagedObjectReference objects and values their names.
                
        :return: a dict   
         e.g.
        {'datacenter-12': 'csk3', 'datacenter-2': 'csk1', 'datacenter-7': 'csk2'}

        """
        return self._server.get_datacenters()

    # ******************************************************
    # ***************** Private Methods *******************
    # ******************************************************

    def _fetch_datacenter_vms(self):
        """ Fetch/cache datacenter vm mapping information.
        
        This can be later used to retrieve datacenter information for each
        VM.
        """
        if not self._vm_datacenters:
            dcs = self.get_datacenters()
            for name in dcs.keys():
                self._vm_datacenters[name] = self._server._get_managed_objects(MORTypes.VirtualMachine, from_mor=name)

            # logger.debug(': _vm_datacenters: %s' % self._vm_datacenters)

    def _get_instance(self, instanceUuid):
        """ Retrieves instance by its instanceUuid.
        
        TODO: make this faster by caching instances.
        """
        instances = self.list_instances(instanceUuid)
        if not instances:
            raise InstanceNotFoundError("Instance %s not found" % instanceUuid)
        else:
            return instances[0]
开发者ID:AsherBond,项目名称:cato,代码行数:104,代码来源:vsphere.py

示例4: get_stats

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [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
#.........这里部分代码省略.........
开发者ID:Mavenhut,项目名称:collectd-python-extra,代码行数:103,代码来源:vcenter.py

示例5: __init__

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]

#.........这里部分代码省略.........
        # VM NAME
        vm_name = None
        try:
            vm_name = str(vm_options["vm_name"])
            vm_temp = self.esx_server.get_vm_by_name(vm_name)
            if vm_temp:
                raise ExistenceException('VM "%s" already exists' % vm_name)
        except KeyError:
            raise CreatorException("Must specify VM name")
        except pysphere.VIException as inst:
            if "[Object Not Found]" in str(inst):
                pass

        # HOSTNAME
        hosts = self.esx_server.get_hosts()
        try:
            esx_hostname = vm_options["esx_hostname"]
            if not esx_hostname:
                raise KeyError
            elif not (esx_hostname in hosts.values()):
                raise CreatorException("Couldn't find host '%s'" % esx_hostname)
        except KeyError:
            if len(hosts.values()) > 1:
                raise CreatorException("More than 1 host - must specify ESX Hostname")
            elif not hosts.values():
                raise CreatorException("Couldn't find available host")
            esx_hostname = hosts[0]
            # MOR and PROPERTIES
        hostmor = [k for k, v in hosts.items() if v == esx_hostname][0]
        hostprop = VIProperty(self.esx_server, hostmor)

        # DATACENTER - FIX EXCEPTION
        # todo: fix self.esx_server.get_datacenters().values()
        dcs = self.esx_server.get_datacenters()
        dc_values = dcs.values()
        try:
            dc_name = vm_options["datacenter_name"]
            if not dc_name in dc_values:
                raise CreatorException("Couldn't find datacenter '%s'" + dc_name)
        except KeyError:
            if len(dc_values) > 1:
                raise CreatorException("More than 1 datacenter - must specify ESX Hostname")
            elif not dc_values:
                raise CreatorException("Couldn't find available datacenter")
            dc_name = dc_values[0]
            # MOR and PROPERTIES
        dcmor = [k for k, v in dcs.items() if v == dc_name][0]
        dcprops = VIProperty(self.esx_server, dcmor)

        # DATASTORE
        dcs = hostprop.datastore
        try:
            ds_name = vm_options["datastore_name"]
            ds_list = []
            for ds in dcs:
                ds_list.append(ds.name)
            if not ds_name in ds_list:
                raise CreatorException("Couldn't find datastore or datastore is not available")
        except KeyError:
            if len(dcs) > 1:
                raise CreatorException("More than 1 datastore on ESX - must specify datastore name")
            elif not dcs:
                raise CreatorException("Couldn't find available datastore")
            ds_name = dcs[0].name

        # RESOURCE POOL
开发者ID:rkhozinov,项目名称:deployment_system,代码行数:70,代码来源:hatchery.py

示例6: str

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
sThisEsxiHost = str(args.esxihost)
bFound = False

##if:User and passwd passed?
if sThisUser == "" or sThisPasswd == "":
	print "Invalid username or password"
	sys.exit(1)

##if:Do we have a host?
if sThisCluster != "":
	##stmt:Yes, connect to vCenter
	server = VIServer()
	server.connect(sThisEsxiHost, sThisUser, sThisPasswd)

	##stmt:Get datacenter object
	oDataCenter = server.get_datacenters()

	##loop:Get each datacenter
	for dc_mor, dc_name in oDataCenter.items():
		##stmt:Get clusters in the datacenter
		oClusters = server.get_clusters(from_mor=dc_mor)

		##loop:Get each cluster
		for c_mor, c_name in oClusters.items():
			##stmt:Get next cluster

			##if:Is this the cluster we are looking for?
			if sThisCluster == c_name:
				##stmt:Yes, get hosts
				oHosts = server.get_hosts(from_mor=c_mor)
开发者ID:OneMainF,项目名称:vmware-ansible-rhel-server-builder,代码行数:32,代码来源:getHostsFromCluster.py

示例7: connect

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
class basicOps:

    server=None

    def connect(self):
        configuration=Config()
        server = configuration._config_value("general", "server")
        if server is None:
            raise ValueError("server must be supplied on command line"+"or in configuration file.")
        username = configuration._config_value("general", "username")
        if username is None:
            raise ValueError("username must be supplied on command line"
                         " or in configuration file.")
        password = configuration._config_value("general", "password")
        if password is None:
            raise ValueError("password must be supplied on command line"
                         " or in configuration file.")
        self.server=VIServer()
        self.server.connect(server,username,password)

    def startVm(self,vmname):
        vm=self.server.get_vm_by_name(vmname)
        status=vm.get_status()
        if status=="POWERED OFF":
            task=vm.power_on(run_sync=False)
            return task

    def stopVm(self, vmname):
        vm=self.server.get_vm_by_name(vmname)
        status=vm.get_status()
        if status=="POWERED ON":
            task=vm.power_off(run_sync=False)
            return task


    def stopGuest(self,vmname):
        vm=self.server.get_vm_by_name(vmname)
        task=vm.shutdown_guest(run_sync=False)
        return task

    def rebootGuest(self,vmname):
        vm=self.server.get_vm_by_name(vmname)
        task=vm.reboot_guest(run_sync=False)
        return task

    def getDataCenters(self):
        return self.server.get_datacenters()

    def clone(self,templateName,cloneName="Template Clone"):
        vm=self.server.get_vm_by_name(templateName)
        resourcePool=self.getResourcePool()
        print resourcePool
        task=vm.clone(cloneName,resourcepool=resourcePool,sync_run=False)
        try:
            status=task.get_state()
            print(status)
            print "Creating machine from template:Job Status:" + status
            if  status!="error":
              while (status!="success" or status !="error"):
                  status=task.get_state()
                  if  status=="success":
                   break;
            print "Creating machine from template: Job Status:" + status
            #vm_new=self.server.get_vm_by_name(cloneName)
            #return vm_new
        except:
            print("Error Occured:")


    def getResourcePool(self):

        configuration=Config()
        datacenter = configuration._config_value("vmware", "datacenter")
        if datacenter is None:
            raise ValueError("server must be supplied"+"in configuration file.")
        cluster = configuration._config_value("vmware", "cluster")
        if cluster is None:
            raise ValueError("cluster name must be supplied in configuration file.")
        resourcePool = configuration._config_value("vmware", "resourcePool")
        if resourcePool is None:
            raise ValueError("Resource Pool name must be supplied in configuration file")
        clusters=self.server.get_clusters()
            #print clusters
        keycluster=self.find_key(clusters,cluster)
           # print(keycluster)
        resource_pools=self.server.get_resource_pools(keycluster)
       # print(resource_pools)
        resourcePool=self.find_key(resource_pools,resourcePool,True)
       # print (resourcePool)
        return resourcePool


 #               resource_pools=self.server.get_resource_pools()
    def find_key(self,dic, val, partial=False):
      retval=None
      if partial==False:
       retval=[k for k, v in dic.iteritems() if v == val][0]
      else:
        retval =[k for k, v in dic.iteritems() if (v.find(val)>0)][0]
      return retval
#.........这里部分代码省略.........
开发者ID:ichaudhry786,项目名称:vmware,代码行数:103,代码来源:basicOps.py

示例8:

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
except VIException as ins:
	logger.error(ins)
	logger.debug('Loggin error. Program will exit now.')
	sys.exit()

# Setting up vars
datacenters = None
clusters = None
hosts = None
datastores = None
vms = None

try:
    # Getting datacenters
    logger.debug('Getting datastores')
    datacenters = con.get_datacenters().values()

    # Getting clusters
    logger.debug('Getting clusters')
    clusters = con.get_clusters().values()

    # Getting Hosts
    logger.debug('Getting Hosts')
    hosts = con.get_hosts().values()

    # Getting Datastores 
    logger.debug('Getting Datastores')
    datastores = con.get_datastores().values()

    # Getting Registered VMs
    logger.debug('Getting VMs')
开发者ID:dfederlein,项目名称:vsphere_report,代码行数:33,代码来源:vmware_vcenter_rerport.py

示例9: __init__

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
class ESXi_Server:
    server_ip    = ''
    user_name    = ''
    password     = ''
    connect_flag = False
    server       = None
    #vm_list      = []

    #def __init__(self):

    #Use the given args to connect the esxi server you want
    #@ip[string]: ESXi server's IP address
    #@name[string]: the username used to login the ESXi server
    #@pwd[string]: the password used to login the ESXi server
    def connect_server(self, ip, name, pwd):
        self.server_ip = ip
        self.user_name = name
        self.password  = pwd
        self.server = VIServer()
        self.server.connect(self.server_ip, self.user_name, self.password)
        self.connect_flag = self.server.is_connected()
        if self.connect_flag:
            return True
        return False

    #To get all the definition registered vms from the connected server
    #@param[string]: can be set as ALL, POWER_ON, POWER_OFF, SUSPENDED
    #According to the param, returns a list of VM Paths. You might also filter by datacenter,
    #cluster, or resource pool by providing their name or MORs.
    #if  cluster is set, datacenter is ignored, and if resource pool is set
    #both, datacenter and cluster are ignored.
    def get_registered_vms(self, param, status=None, datacenter=None, cluster=None,
                           resource_pool=None):
        if param not in ['ALL', 'POWER_ON', 'POWER_OFF', 'SUSPENDED']:
            print "Get VMs error: param can only be set as ALL, POWER_ON, POWER_OFF, or SUSPENDED."
            return None
        if self.connect_flag == False:
            print "Get VMs error: Server not connected."
            return None
        if param == 'ALL':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool)
        elif param == 'POWER_ON':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool, status='poweredOn')
        elif param == 'POWER_OFF':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool, status='poweredOff')
        elif param == 'SUSPENDED':
            return self.server.get_registered_vms(datacenter, cluster, resource_pool, status='suspended')
        else:
            return None

    #Disconnect to the Server
    def disconnect(self):
        if self.connect_flag == True:
            self.server = self.server.disconnect()
            self.connect_flag == False

    #To keep session alive
    def keep_session_alive(self):
        assert self.server.keep_session_alive()

    #To get the server type
    def get_server_type(self):
        return self.server.get_server_type()

    #To get performance manager
    def get_performance_manager(self):
        return self.server.get_performance_manager()

    #To get the all the server's hosts
    def get_all_hosts(self):
        """
        Returns a dictionary of the existing hosts keys are their names
        and values their ManagedObjectReference object.
        """
        return self.server.get_hosts()

    #To get all datastores
    def get_all_datastores(self):
        """
        Returns a dictionary of the existing datastores. Keys are
        ManagedObjectReference and values datastore names.
        """
        return self.server.get_datastores()

    #To get all clusters
    def get_all_clusters(self):
        """
        Returns a dictionary of the existing clusters. Keys are their
        ManagedObjectReference objects and values their names.
        """
        return self.server.get_clusters()

    #To get all datacenters
    def get_all_datacenters(self):
        """
        Returns a dictionary of the existing datacenters. keys are their
        ManagedObjectReference objects and values their names.
        """
        return self.server.get_datacenters()

#.........这里部分代码省略.........
开发者ID:cloudtrends,项目名称:scaffold-shell,代码行数:103,代码来源:esxitools.py

示例10: Hosts

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
vms_info = {} 
hosts_dict = None
datastores_dict = None
dvpgs = {}
paths = {}
props = None

# hosts, datastores, dvpgs, paths and vms 
try:
    hosts_dict = server.get_hosts().items()
    logger.debug('Host dictionary generated with size %d' % (len(hosts_dict)))
    
    datastores_dict = server.get_datastores().items()
    logger.debug('Datastores dictionary generated with size %d' % (len(datastores_dict)))
    
    datacenters = server.get_datacenters().items()
    logger.debug('Datacenters dictionary generated with size %d' % (len(datacenters)))
    
    dvpgs = get_dvp_dict(datacenters, dcname, server)
    logger.debug('Distributed Virtual Portgroup dictionary generated with size %d' % (len(dvpgs)))
    
    paths = get_paths_dict(server, properties2)
    logger.debug('VM Paths dictionary generated with size %d' % (len(paths)))
    logger.info('Pre-required dictionaries were successfully gotten: Hosts (%s), Datastores (%s), Datacenters(%s), DVPG(%s) and VM Paths(%s)' %(len(hosts_dict), len(datastores_dict), len(datacenters), len(dvpgs), len(paths)))
    
    logger.info('Building main Virtual Machine properties dictionary. This might take a few minutes.')
    vms_info = get_vms_dict(server, properties, paths, hosts_dict, datastores_dict, dvpgs)
    logger.debug('VM main dictionary generated with size %d' %(len(vms_info)))
    
    # Disconnecting from server
    logger.info('Terminating server %s session' % servervctr)
开发者ID:jm66,项目名称:vsphere_inventory_report,代码行数:33,代码来源:vsphere_inventory_report.py

示例11: main

# 需要导入模块: from pysphere import VIServer [as 别名]
# 或者: from pysphere.VIServer import get_datacenters [as 别名]
def main(options):
	global host_vms
	LOGGER.debug("Options: {0}".format(options))
	LOGGER.debug("Args: {0}".format(args))
	
	#check for senseful inputs
	if not options.vcServer or not options.satServer:
		LOGGER.error("You need to specify at least Satellite and vCenter hostnames!")
		exit(1)
	
	#get Satellite and vCenter credentials
	if options.dryrun: LOGGER.info("I'm only doing a simulation, I promise!")
	(satUsername, satPassword) = get_credentials("Satellite", options.satAuthfile)
	(vcUsername, vcPassword) = get_credentials("Virtualization", options.vcAuthfile)
	
	#connect to vCenter
	myVC = VIServer()
	myVC.connect(options.vcServer, vcUsername, vcPassword)
	
	#connect to Satellite
	satellite_url = "http://{0}/rpc/api".format(options.satServer)
	mySat = xmlrpclib.Server(satellite_url, verbose=options.debug)
	key = mySat.auth.login(satUsername, satPassword)
	check_if_api_is_supported(mySat)
	
	#print information about host
	LOGGER.info("Connected to " + options.vcServer + " (" + myVC.get_server_type() + "), version " + myVC.get_api_version() + ".")
	
	#get list of all ESXi hosts by datacenter
	LOGGER.info("Searching for ESXi hosts by datacenter...")
	esxiHosts = myVC.get_hosts()
	datacenters = myVC.get_datacenters()
	for dc in datacenters:
		tempHosts = myVC.get_hosts(from_mor=dc).values()
		hosts_by_dc[datacenters.get(dc)] = (tempHosts)
	LOGGER.debug("Hosts by DC: " + str(hosts_by_dc))
	
	#get list of all ESXi hosts by cluster
	LOGGER.info("Searching for ESXi hosts by cluster...")
	clusters = myVC.get_clusters()
	for cluster in clusters:
		tempHosts = myVC.get_hosts(from_mor=cluster).values()
		hosts_by_cluster[clusters.get(cluster)] = (tempHosts)
	LOGGER.debug("Hosts by cluster: " + str(hosts_by_cluster))
	
	#get list of all VMs by ESXi host
	for dc in datacenters:
		for host in hosts_by_dc[datacenters.get(dc)]:
			LOGGER.debug("Found ESXi host '" + host + "'")
			host_vms[host]=[]
	LOGGER.debug("Added hosts to dict: " + str(host_vms))
	
	#get list of all Linux VMs managed by Satellite
	satlist = mySat.system.listSystems(key)
	target_vms=[]
	LOGGER.info("Digging through list of systems managed by Satellite...")
	for system in satlist:
		LOGGER.debug("Found system '" + system["name"] + "'")
		#get custom keys
		thisKeys = mySat.system.getCustomValues(key, system["id"])
		#add virt_vmname if given
		if "SYSTEM_VIRT_VMNAME" in thisKeys and thisKeys["SYSTEM_VIRT_VMNAME"] != "":
			target_vms.append(thisKeys["SYSTEM_VIRT_VMNAME"])
		else: target_vms.append(system)
		LOGGER.debug("VM names: " + str(target_vms))
	
	#get list of all VMs and assign to host dicts
	LOGGER.info("Getting list of all VMs and assign them to host arrays - grab some coffee.")
	vmlist = myVC.get_registered_vms()
	counter=0
	hit=0
	for vm in vmlist:
		#get VM and its properties
		thisVM = myVC.get_vm_by_path(vm)
		#only add if in target_vms
		if thisVM.properties.name in target_vms:
			LOGGER.debug("Found VM managed by Satellite: '" + thisVM.properties.name + "'")
			host_vms[thisVM.properties.runtime.host.name].append(thisVM.properties.name)
		else: LOGGER.debug("'" + thisVM.properties.name + "' dropped as it is not managed by Satellite")
		
		LOGGER.debug("Current array for host '" + thisVM.properties.runtime.host.name + "': " + str(host_vms[thisVM.properties.runtime.host.name]))
		#show progress
		if hit == 9:
			LOGGER.info("Checked " + str(counter+1) + " of " + str(len(vmlist)) + " VMs so far...")
			hit=0
		else: hit=(hit+1)
		counter=(counter+1)
	LOGGER.debug("Added VMs to host dicts: " + str(host_vms))
	
	#get list of all Linux VMs managed by Satellite
	satlist = mySat.system.listSystems(key)
	LOGGER.info("Updating relevant system custom info keys...")
	for system in satlist:
		LOGGER.debug("Found system '" + system["name"] + "'")
		#get custom keys
		thisKeys = mySat.system.getCustomValues(key, system["id"])
		#update key if exists
		if "SYSTEM_VIRT_HOST" in thisKeys and thisKeys["SYSTEM_VIRT_HOST"] != "":
			#get ESXi host running VM
			if "SYSTEM_VIRT_VMNAME" in thisKeys and thisKeys["SYSTEM_VIRT_VMNAME"] != "":
#.........这里部分代码省略.........
开发者ID:stdevel,项目名称:satprep,代码行数:103,代码来源:satprep_wa_vcvms.py


注:本文中的pysphere.VIServer.get_datacenters方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。