def get_host(self, hostname): ''' Read info about a specific host or VM from cache or VMware API. ''' inv = self._get_cache(hostname, None) if inv is not None: return inv if not self.guests_only: try: host = HostSystem.get(self.client, name=hostname) inv = self._get_host_info(host) except ObjectNotFoundError: pass if inv is None: try: vm = VirtualMachine.get(self.client, name=hostname) inv = self._get_vm_info(vm) except ObjectNotFoundError: pass if inv is not None: self._put_cache(hostname, inv) return inv or {}
def main(): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_NONE # real vcenter kwargs = {'host': '192.168.1.39', 'user': '******', 'pwd': 'vmware', 'port': 443, 'sslContext': context} # fake vcenter kwargs = {'host': 'localhost', 'user': '******', 'pwd': 'test', 'port': 443, 'sslContext': context } print('# PYVMOMI ...') try: si = SmartConnect(**kwargs) content = si.RetrieveContent() virtual_machines = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) for virtual_machine in virtual_machines.view: name = virtual_machine.name print('name: %s' % name) if virtual_machine.guest: for net in virtual_machine.guest.net: print('mac: %s' % net.macAddress) except Exception as e: print e print('# PSPHERE ...') client = Client(kwargs['host'], kwargs['user'], kwargs['pwd']) hosts = HostSystem.all(client) for host in hosts: print 'host:',host.name for vm in host.vm: print 'name: ',vm.name
def get_inventory(client, config): ''' Reads the inventory from cache or vmware api ''' if cache_available('inventory', config): inv = get_cache('inventory', config) else: inv = {'all': {'hosts': []}, '_meta': {'hostvars': {}}} default_group = os.path.basename(sys.argv[0]).rstrip('.py') if config.has_option('defaults', 'guests_only'): guests_only = config.get('defaults', 'guests_only') else: guests_only = True if not guests_only: if config.has_option('defaults', 'hw_group'): hw_group = config.get('defaults', 'hw_group') else: hw_group = default_group + '_hw' inv[hw_group] = [] if config.has_option('defaults', 'vm_group'): vm_group = config.get('defaults', 'vm_group') else: vm_group = default_group + '_vm' inv[vm_group] = [] # Loop through physical hosts: hosts = HostSystem.all(client) for host in hosts: if not guests_only: inv['all']['hosts'].append(host.name) inv[hw_group].append(host.name) if host.tag: taggroup = 'vmware_' + host.tag if taggroup in inv: inv[taggroup].append(host.name) else: inv[taggroup] = [host.name] inv['_meta']['hostvars'][host.name] = get_host_info(host) save_cache(vm.name, inv['_meta']['hostvars'][host.name], config) for vm in host.vm: inv['all']['hosts'].append(vm.name) inv[vm_group].append(vm.name) if vm.tag: taggroup = 'vmware_' + vm.tag if taggroup in inv: inv[taggroup].append(vm.name) else: inv[taggroup] = [vm.name] inv['_meta']['hostvars'][vm.name] = get_host_info(host) save_cache(vm.name, inv['_meta']['hostvars'][vm.name], config) save_cache('inventory', inv, config) return json.dumps(inv)
def get_host_by_name(self, hostname): try: print 'hostname: ', print hostname return HostSystem.get(self.client, name=hostname) except ObjectNotFoundError as ex: traceback.print_stack() raise ObjectNotFoundError('Could not find HostSystem:%s. %s' % (hostname, to_str(ex)))
def get_inventory(client, config): ''' Reads the inventory from cache or vmware api ''' if cache_available('inventory', config): inv = get_cache('inventory',config) else: inv= { 'all': {'hosts': []}, '_meta': { 'hostvars': {} } } default_group = os.path.basename(sys.argv[0]).rstrip('.py') if config.has_option('defaults', 'guests_only'): guests_only = config.get('defaults', 'guests_only') else: guests_only = True if not guests_only: if config.has_option('defaults','hw_group'): hw_group = config.get('defaults','hw_group') else: hw_group = default_group + '_hw' inv[hw_group] = [] if config.has_option('defaults','vm_group'): vm_group = config.get('defaults','vm_group') else: vm_group = default_group + '_vm' inv[vm_group] = [] # Loop through physical hosts: hosts = HostSystem.all(client) for host in hosts: if not guests_only: inv['all']['hosts'].append(host.name) inv[hw_group].append(host.name) if host.tag: taggroup = 'vmware_' + host.tag if taggroup in inv: inv[taggroup].append(host.name) else: inv[taggroup] = [ host.name ] inv['_meta']['hostvars'][host.name] = get_host_info(host) save_cache(vm.name, inv['_meta']['hostvars'][host.name], config) for vm in host.vm: inv['all']['hosts'].append(vm.name) inv[vm_group].append(vm.name) if vm.tag: taggroup = 'vmware_' + vm.tag if taggroup in inv: inv[taggroup].append(vm.name) else: inv[taggroup] = [ vm.name ] inv['_meta']['hostvars'][vm.name] = get_host_info(host) save_cache(vm.name, inv['_meta']['hostvars'][vm.name], config) save_cache('inventory', inv, config) return json.dumps(inv)
def get_host(client, name): hosts = HostSystem.all(client.api) if name is None: return api_params_resolution(hosts, 'host', 'host') else: for host in hosts: if host.name == name: return host print("VSPHERE: Could not find specified host '{}'".format(name))
def get_host(client, name): hosts = HostSystem.all(client.api) if name is None: return api_params_resolution(hosts, 'host', 'host') else: for host in hosts: if host.name == name: return host print "VSPHERE: Could not find specified host '%s'" % name
def get_host(client, name): from psphere.managedobjects import HostSystem hosts = HostSystem.all(client) if name is None: return api_params_resolution(hosts, 'host', 'host') else: for host in hosts: if host.name == name: return host print "VSPHERE: Could not find specified host '%s'" % name
def get_hs(self): if self._hs is None: try: self._hs = HostSystem.get(self.client, name=self.hostname) except ObjectNotFoundError as ex: traceback.print_stack() raise ObjectNotFoundError('Could not find HostSystem:%s. %s' % (self.hostname, to_str(ex))) if self._hs is None: raise Exception('ESXiNode Could not get host systemi %s from vCenter!' % self.hostname) return self._hs
def list_nodes(self, ex_node_ids=None, ex_vmpath=None): nodes = [] hosts = HostSystem.all(self.connection) for host in hosts: for vm in host.vm: node = self._to_node(vm) if ex_node_ids is None or node.id in ex_node_ids: if ex_vmpath is None or vm.summary.config.vmPathName == ex_vmpath: nodes.append(node) uuids = [node.id for node in nodes] if ex_node_ids is not None and len(uuids) != len(set(uuids)): raise Exception("Cannot identify target node. Duplicate uuid exists") else: return nodes
def get_inventory(client, config): """ Reads the inventory from cache or vmware api """ inv = {} if cache_available("inventory", config): inv = get_cache("inventory", config) elif client: inv = {"all": {"hosts": []}, "_meta": {"hostvars": {}}} default_group = os.path.basename(sys.argv[0]).rstrip(".py") if config.has_option("defaults", "guests_only"): guests_only = config.get("defaults", "guests_only") else: guests_only = True if not guests_only: if config.has_option("defaults", "hw_group"): hw_group = config.get("defaults", "hw_group") else: hw_group = default_group + "_hw" inv[hw_group] = [] if config.has_option("defaults", "vm_group"): vm_group = config.get("defaults", "vm_group") else: vm_group = default_group + "_vm" inv[vm_group] = [] # Loop through physical hosts: hosts = HostSystem.all(client) for host in hosts: if not guests_only: inv["all"]["hosts"].append(host.name) inv[hw_group].append(host.name) inv["_meta"]["hostvars"][host.name] = get_host_info(host) save_cache(vm.name, inv["_meta"]["hostvars"][host.name], config) for vm in host.vm: inv["all"]["hosts"].append(vm.name) inv[vm_group].append(vm.name) inv["_meta"]["hostvars"][vm.name] = get_host_info(vm) save_cache(vm.name, inv["_meta"]["hostvars"][vm.name], config) save_cache("inventory", inv, config) return json.dumps(inv)
def get_single_host(client, config, hostname): inv = {} if cache_available(hostname, config): inv = get_cache(hostname,config) elif client: hosts = HostSystem.all(client) #TODO: figure out single host getter for host in hosts: if hostname == host.name: inv = get_host_info(host) break for vm in host.vm: if hostname == vm.name: inv = get_host_info(vm) break save_cache(hostname,inv,config) return json.dumps(inv)
def main(options): client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) # Get a HostSystem object representing the host host = HostSystem.get(client, name=options.hostsystem) # Preload the name attribute of all items in the vm attribute. Read the # manual as this significantly speeds up queries for ManagedObject's host.preload("vm", properties=["name"]) # Iterate over the items in host.vm and print their names for vm in sorted(host.vm): print(vm.name) # Close the connection client.logout()
def main(options): client = Client(server=options.server, username=options.username, password=options.password) print('Successfully connected to %s' % client.server) host = HostSystem.all(client) for h in host: # Preload the name attribute of all items in the vm attribute. Read the # manual as this significantly speeds up queries for ManagedObject's h.preload("vm", properties=["name", "guest"]) # Iterate over the items in host.vm and print their names for vm in sorted(h.vm): print("%s: %s" % (vm.name, vm.guest.guestState)) # Close the connection client.logout()
def get_inventory(self, meta_hostvars=True): ''' Reads the inventory from cache or VMware API via pSphere. ''' # Use different cache names for guests only vs. all hosts. if self.guests_only: cache_name = '__inventory_guests__' else: cache_name = '__inventory_all__' inv = self._get_cache(cache_name, None) if inv is not None: return inv inv = {'all': {'hosts': []}} if meta_hostvars: inv['_meta'] = {'hostvars': {}} default_group = os.path.basename(sys.argv[0]).rstrip('.py') if not self.guests_only: if self.config.has_option('defaults', 'hw_group'): hw_group = self.config.get('defaults', 'hw_group') else: hw_group = default_group + '_hw' if self.config.has_option('defaults', 'vm_group'): vm_group = self.config.get('defaults', 'vm_group') else: vm_group = default_group + '_vm' # Loop through physical hosts: for host in HostSystem.all(self.client): if not self.guests_only: self._add_host(inv, 'all', host.name) self._add_host(inv, hw_group, host.name) host_info = self._get_host_info(host) if meta_hostvars: inv['_meta']['hostvars'][host.name] = host_info self._put_cache(host.name, host_info) # Loop through all VMs on physical host. for vm in host.vm: self._add_host(inv, 'all', vm.name) self._add_host(inv, vm_group, vm.name) vm_info = self._get_vm_info(vm) if meta_hostvars: inv['_meta']['hostvars'][vm.name] = vm_info self._put_cache(vm.name, vm_info) # Group by resource pool. vm_resourcePool = vm_info.get('vmware_resourcePool', None) if vm_resourcePool: self._add_child(inv, vm_group, 'resource_pools') self._add_child(inv, 'resource_pools', vm_resourcePool) self._add_host(inv, vm_resourcePool, vm.name) # Group by datastore. for vm_datastore in vm_info.get('vmware_datastores', []): self._add_child(inv, vm_group, 'datastores') self._add_child(inv, 'datastores', vm_datastore) self._add_host(inv, vm_datastore, vm.name) # Group by network. for vm_network in vm_info.get('vmware_networks', []): self._add_child(inv, vm_group, 'networks') self._add_child(inv, 'networks', vm_network) self._add_host(inv, vm_network, vm.name) # Group by guest OS. vm_guestId = vm_info.get('vmware_guestId', None) if vm_guestId: self._add_child(inv, vm_group, 'guests') self._add_child(inv, 'guests', vm_guestId) self._add_host(inv, vm_guestId, vm.name) # Group all VM templates. vm_template = vm_info.get('vmware_template', False) if vm_template: self._add_child(inv, vm_group, 'templates') self._add_host(inv, 'templates', vm.name) self._put_cache(cache_name, inv) return inv
#!/usr/bin/python import sys from psphere.client import Client from psphere.managedobjects import HostSystem, VirtualMachine client = Client(sys.argv[1], sys.argv[2], sys.argv[3]) host_systems = HostSystem.all(client) print("HostSystem.all(client) finds these hosts") for host_system in host_systems: print(host_system.name) vm = VirtualMachine.get(client, name="genesis", overallStatus="green") print('VirtualMachine.get(client, name="genesis", overallStatus="green")' ' got the following host:') print("Name: %s" % vm.name) print("overallStatus: %s" % vm.overallStatus)
def ex_hardware_profiles(self): hardware_profiles = [] hosts = HostSystem.all(self.connection) for host in hosts: hardware_profiles.append(self._to_hardware_profile(host)) return hardware_profiles
def get_hs(self): if self._hs is None: self._hs = HostSystem.all(self.client)[0] if self._hs is None: raise Exception('ESXiNode Could not get host system!') return self._hs
#!/bin/env python from psphere.client import Client from psphere.managedobjects import HostSystem esxi_host = sys.argv[1] #HyperVisor hostname username = sys.argv[2] #HyperVisor login username password = sys.argv[3] #HyperVisor login password client = Client(esxi_host, username, password) hosts = HostSystem.all(client) cpu_usage = hosts[0].summary.quickStats.overallCpuUsage print cpu_usage
def initialize_hosts(self): for h in self.hosts: fd = self.create_log(h) host_ins = HostSystem.get(self.client, name=h) host_obj = Host_info(host_ins) self.hostsconn_fds.append((fd, host_obj))
def get_inventory(self, meta_hostvars=True): # noqa # pylint: disable=too-complex ''' Reads the inventory from cache or VMware API via pSphere. ''' # Use different cache names for guests only vs. all hosts. if self.guests_only: cache_name = '__inventory_guests__' else: cache_name = '__inventory_all__' inv = self._get_cache(cache_name, None) if inv is not None: return inv inv = {'all': {'hosts': []}} if meta_hostvars: inv['_meta'] = {'hostvars': {}} default_group = os.path.basename(sys.argv[0]).rstrip('.py') if not self.guests_only: if self.config.has_option('defaults', 'hw_group'): hw_group = self.config.get('defaults', 'hw_group') else: hw_group = default_group + '_hw' if self.config.has_option('defaults', 'vm_group'): vm_group = self.config.get('defaults', 'vm_group') else: vm_group = default_group + '_vm' if self.config.has_option('defaults', 'prefix_filter'): prefix_filter = self.config.get('defaults', 'prefix_filter') else: prefix_filter = None if self.filter_clusters: # Loop through clusters and find hosts: hosts = [] for cluster in ClusterComputeResource.all(self.client): if cluster.name in self.filter_clusters: for host in cluster.host: hosts.append(host) else: # Get list of all physical hosts hosts = HostSystem.all(self.client) # Loop through physical hosts: for host in hosts: if not self.guests_only: self._add_host(inv, 'all', host.name) self._add_host(inv, hw_group, host.name) host_info = self._get_host_info(host) if meta_hostvars: inv['_meta']['hostvars'][host.name] = host_info self._put_cache(host.name, host_info) # Loop through all VMs on physical host. for vm in host.vm: if prefix_filter: if vm.name.startswith(prefix_filter): continue self._add_host(inv, 'all', vm.name) self._add_host(inv, vm_group, vm.name) vm_info = self._get_vm_info(vm) if meta_hostvars: inv['_meta']['hostvars'][vm.name] = vm_info self._put_cache(vm.name, vm_info) # Group by resource pool. vm_resourcePool = vm_info.get('vmware_resourcePool', None) if vm_resourcePool: self._add_child(inv, vm_group, 'resource_pools') self._add_child(inv, 'resource_pools', vm_resourcePool) self._add_host(inv, vm_resourcePool, vm.name) # Group by datastore. for vm_datastore in vm_info.get('vmware_datastores', []): self._add_child(inv, vm_group, 'datastores') self._add_child(inv, 'datastores', vm_datastore) self._add_host(inv, vm_datastore, vm.name) # Group by network. for vm_network in vm_info.get('vmware_networks', []): self._add_child(inv, vm_group, 'networks') self._add_child(inv, 'networks', vm_network) self._add_host(inv, vm_network, vm.name) # Group by guest OS. vm_guestId = vm_info.get('vmware_guestId', None) if vm_guestId: self._add_child(inv, vm_group, 'guests') self._add_child(inv, 'guests', vm_guestId) self._add_host(inv, vm_guestId, vm.name) # Group all VM templates. vm_template = vm_info.get('vmware_template', False) if vm_template: self._add_child(inv, vm_group, 'templates') self._add_host(inv, 'templates', vm.name) self._put_cache(cache_name, inv) return inv
def get_inventory(self, meta_hostvars=True): ''' Reads the inventory from cache or VMware API via pSphere. ''' # Use different cache names for guests only vs. all hosts. if self.guests_only: cache_name = '__inventory_guests__' else: cache_name = '__inventory_all__' inv = self._get_cache(cache_name, None) if inv is not None: return inv inv = {'all': {'hosts': []}} if meta_hostvars: inv['_meta'] = {'hostvars': {}} default_group = os.path.basename(sys.argv[0]).rstrip('.py') if not self.guests_only: if self.config.has_option('defaults', 'hw_group'): hw_group = self.config.get('defaults', 'hw_group') else: hw_group = default_group + '_hw' if self.config.has_option('defaults', 'vm_group'): vm_group = self.config.get('defaults', 'vm_group') else: vm_group = default_group + '_vm' if self.config.has_option('defaults', 'prefix_filter'): prefix_filter = self.config.get('defaults', 'prefix_filter') else: prefix_filter = None if self.filter_clusters: # Loop through clusters and find hosts: hosts = [] for cluster in ClusterComputeResource.all(self.client): if cluster.name in self.filter_clusters: for host in cluster.host: hosts.append(host) else: # Get list of all physical hosts hosts = HostSystem.all(self.client) # Loop through physical hosts: for host in hosts: if not self.guests_only: self._add_host(inv, 'all', host.name) self._add_host(inv, hw_group, host.name) host_info = self._get_host_info(host) if meta_hostvars: inv['_meta']['hostvars'][host.name] = host_info self._put_cache(host.name, host_info) # Loop through all VMs on physical host. for vm in host.vm: if prefix_filter: if vm.name.startswith(prefix_filter): continue self._add_host(inv, 'all', vm.name) self._add_host(inv, vm_group, vm.name) vm_info = self._get_vm_info(vm) if meta_hostvars: inv['_meta']['hostvars'][vm.name] = vm_info self._put_cache(vm.name, vm_info) # Group by resource pool. vm_resourcePool = vm_info.get('vmware_resourcePool', None) if vm_resourcePool: self._add_child(inv, vm_group, 'resource_pools') self._add_child(inv, 'resource_pools', vm_resourcePool) self._add_host(inv, vm_resourcePool, vm.name) # Group by datastore. for vm_datastore in vm_info.get('vmware_datastores', []): self._add_child(inv, vm_group, 'datastores') self._add_child(inv, 'datastores', vm_datastore) self._add_host(inv, vm_datastore, vm.name) # Group by network. for vm_network in vm_info.get('vmware_networks', []): self._add_child(inv, vm_group, 'networks') self._add_child(inv, 'networks', vm_network) self._add_host(inv, vm_network, vm.name) # Group by guest OS. vm_guestId = vm_info.get('vmware_guestId', None) if vm_guestId: self._add_child(inv, vm_group, 'guests') self._add_child(inv, 'guests', vm_guestId) self._add_host(inv, vm_guestId, vm.name) # Group all VM templates. vm_template = vm_info.get('vmware_template', False) if vm_template: self._add_child(inv, vm_group, 'templates') self._add_host(inv, 'templates', vm.name) self._put_cache(cache_name, inv) return inv
#!/bin/env python from psphere.client import Client from psphere.managedobjects import HostSystem client = Client("ホスト名/IPアドレス", "ログインユーザ名", "パスワード") hosts = HostSystem.all(client) for host in hosts: cpu_usage = host.summary.quickStats.overallCpuUsage cpu_core_num = host.summary.hardware.numCpuCores cpu_clock = host.summary.hardware.cpuMhz print "Host name: %s" % host.name print "CPU Usage(MHz): %d" % cpu_usage print "CPU Usage(%%): %f \n" % ((float(cpu_usage)/(cpu_core_num*cpu_clock))*100) for vm in host.vm: vm_cpu_usage = vm.summary.quickStats.overallCpuUsage vm_cpu_core_num = vm.summary.config.numCpu print "VM name: %s" % vm.name print "CPU Usage(MHz): %d" % vm_cpu_usage print "CPU Usage(%%): %f \n" % ((float(vm_cpu_usage)/(vm_cpu_core_num*cpu_clock))*100)