def post(self, id): parser = reqparse.RequestParser() parser.add_argument("name") parser.add_argument("description") parser.add_argument("owner") parser.add_argument("location") parser.add_argument("power") parser.add_argument("OS") parser.add_argument("api-key", required=True, help="Missing API key.") args = parser.parse_args() global apikey # Power management if (args["power"] == "poweredOn" and len(args) > 0 and apikey == args["api-key"]): connection = connect.ConnectNoSSL("192.168.182.132", 443, "root", "toasterddos") cursor.execute("SELECT `name` FROM `vms` WHERE `id`='" + str(id) + "'") vm = getVM(connection.content, cursor.fetchone()["name"]) vm.PowerOn() connect.Disconnect(connection) return "On.", 200 elif (args["power"] == "poweredOff" and len(args) > 0 and apikey == args["api-key"]): connection = connect.ConnectNoSSL("192.168.182.132", 443, "root", "toasterddos") cursor.execute("SELECT `name` FROM `vms` WHERE `id`='" + str(id) + "'") vm = getVM(connection.content, cursor.fetchone()["name"]) vm.PowerOff() connect.Disconnect(connection) return "Off.", 200 return "Bad request.", 403
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() dataStore = content.rootFolder.childEntity for data in dataStore: vmFolder = data.hostFolder.childEntity for dataVm in vmFolder: host = dataVm.host for h in host: storage = h.config.storageDevice.hostBusAdapter chap = storage[3] ##################################################################################### # CIS 6.1 ##################################################################################### print('Bidirectional Chap Auth [cis 6.1]: '), print(cisClasses.cis_6_1(h))
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) ############################### # Get inf about current user session # privilege: readOnly ############################### print("##########################################") print("Get info about current user session") print("##########################################") session = content.sessionManager.currentSession print(session)
def GoGather(esxHost, esxPort, name, password): try: myConnection = connect.ConnectNoSSL(esxHost, esxPort, name, password) except Exception as Ex: print("esxHost Collector unable to login to {0} : {1}".format(esxHost,str(Ex))) return atexit.register(Disconnect, myConnection) content = myConnection.RetrieveContent() perfManager = content.perfManager #ListAvailablePerfStats(perfManager) try: for datacenter in content.rootFolder.childEntity: if hasattr(datacenter.vmFolder, 'childEntity'): hostFolder = datacenter.hostFolder computeResourceList = hostFolder.childEntity server=computeResourceList[0] while True: hostInfo = GetHostInfo(server) print(hostInfo) cpuUsage = GetCPU_Util(server,perfManager) print(cpuUsage) except Exception as Ex: print(str(Ex))
def __init__(self, args): try: self._connection = connect.ConnectNoSSL(args['address'], 443, args['username'], args['password']) except Exception as e: return f'Could not connect to server: {e}' self._content = self.connection.RetrieveContent()
def admin_dash_board(request): if (request.GET.get("mybtn")): #write all the code here rec = {} for i in range(len(ip)): #iterating through all the hosts if checkHostIsUp(ip[i]): my_cluster = connect.ConnectNoSSL(ip[i], 443, "root", "rootroot") dc = my_cluster.content.rootFolder.childEntity[0] vms = dc.vmFolder.childEntity saveStates(ip[i], i, vms) #saving states of the hosts to the database turnOffVM(ip[i], vms) #turning off the virtual machines turnOffHost(ip[i], dc) #turns the ESXi Host Off rec[ip[i]] = vms return render( request, "dashboard.html", { "message": "All Virtual machines powered Off Gracefully!!", 'myData': rec }) if (request.GET.get('onbtn')): for i in range(len(ip)): if checkHostIsUp(ip[i]): fbdb = firebase.database().child("DataCenter").child( "Hosts").child(mac[i]).get().val() turnOnVM(fbdb, ip[i]) else: return HttpResponse("Wait while the host is starting!!") #return (request, "dashboard.html") return HttpResponse("Everything Restored as it was !") myData = {} for i in range(len(ip)): if checkHostIsUp(ip[i]): my_cluster = connect.ConnectNoSSL(ip[i], 443, "root", "rootroot") dc = my_cluster.content.rootFolder.childEntity[0] vms = dc.vmFolder.childEntity myData[ip[i]] = vms return render(request, "dashboard.html", {'myData': myData})
def main(): args = GetArgs() si = connect.ConnectNoSSL(args.host, 443, args.user, args.password) atexit.register(Disconnect, si) content = si.RetrieveContent() for datacenter in content.rootFolder.childEntity: datastores = datacenter.datastore hostFolder = datacenter.hostFolder computeResourceList = hostFolder.childEntity for computeResource in computeResourceList: hostList = computeResource.host host = hostList[0] datastore = datastores[0] summary = host.summary stats = summary.quickStats hardware = host.hardware #CPU cpuCapacityMhz = (host.hardware.cpuInfo.hz * host.hardware.cpuInfo.numCpuCores) / 1000 / 1000 cpuUsageMhz = stats.overallCpuUsage cpuUsageMhzPercentage = int(100 * cpuUsageMhz / cpuCapacityMhz) #RAM memoryCapacity = hardware.memorySize memoryCapacityInMB = hardware.memorySize/MBFACTOR memoryUsage = stats.overallMemoryUsage freeMemoryPercentage = 100 - ((memoryUsage / memoryCapacityInMB) * 100) freeMemoryPercentageHumanized = int(round(freeMemoryPercentage, 0)) #HDD dsSummary = datastore.summary capacity = dsSummary.capacity freeSpace = dsSummary.freeSpace uncommittedSpace = dsSummary.uncommitted freeSpacePercentage = (float(freeSpace) / capacity) * 100 freeSpacePercentageHumanized = int(round(freeSpacePercentage, 0)) #UpTime uptime = stats.uptime uptimeDays = int(uptime / 60 / 60 / 24) if cpuUsageMhzPercentage < 80 or freeMemoryPercentageHumanized > 20 or freeSpacePercentageHumanized > 20: print("OK - " + str(cpuUsageMhzPercentage) + "% CPU usage, " + str(freeMemoryPercentageHumanized) + "% Free Memory, " + str(freeSpacePercentageHumanized) + "% Free Disk space") sys.exit(0) elif cpuUsageMhzPercentage > 75 or freeMemoryPercentageHumanized < 25 or freeSpacePercentageHumanized < 25: print("Warning - " + str(cpuUsageMhzPercentage) + "% CPU usage, " + str(freeMemoryPercentageHumanized) + "% Free Memory, " + str(freeSpacePercentageHumanized) + "% Free Disk space") sys.exit(1) else: print("Critical - " + str(cpuUsageMhzPercentage) + "% CPU usage, " + str(freeMemoryPercentageHumanized) + "% Free Memory, " + str(freeSpacePercentageHumanized) + "% Free Disk space") sys.exit(2)
def turnOnVM(fbdb, hostIp): my_cluster = connect.ConnectNoSSL(hostIp, 443, "root", "rootroot") dc = my_cluster.content.rootFolder.childEntity[0] vms = dc.vmFolder.childEntity for i in vms: for j in fbdb: if i.name == j: print(i.name) print(fbdb[j]) switchToState(i, fbdb[j])
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() hostView = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True) viewHost = content.viewManager.viewList obj = [host for host in hostView.view] for host in obj: hostAnalisys = host.QueryHostConnectionInfo() ##################################################################################### # CIS 2.1 - need to select a server to let it appears in the list ##################################################################################### configuration = hostAnalisys.host.host.configManager # print(configuration.dateTimeSystem.dateTimeInfo) print('cis 2.1 passed: '), print(cisClasses.cis_2_1(host)) ##################################################################################### # CIS 2.2 ##################################################################################### # print(hostAnalisys.host.host.configManager.firewallSystem.firewallInfo.ruleset) print('cis_2_2_passed: '), print( cisClasses.cis_2_2( host, hostAnalisys.host.host.configManager.firewallSystem. firewallInfo.ruleset)) ##################################################################################### # CIS 2.5 ##################################################################################### # conf = configuration.snmpSystem.configuration # conf.enabled = False # used = configuration.snmpSystem.ReconfigureSnmpAgent(conf) # print(configuration.snmpSystem.configuration) # print(configuration.snmpSystem.limits) print('cis_2_3_passed: '), print(cisClasses.cis_2_3(host))
def connection(args): try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except Exception: raise SystemExit("Unable to connect to host " "with supplied credentials.") return si
def main(): #args = GetArgs() # try: si = None try: print "Trying to connect to VCENTER SERVER . . ." si = connect.ConnectNoSSL(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password']) except IOError, e: pass atexit.register(Disconnect, si)
def getvmconfig(hostIP, hostPass, vmIP): print("Host IP: " + hostIP + ", Host Password: "******", VM IP: " + vmIP) my_cluster = connect.ConnectNoSSL(hostIP, 443, "root", hostPass) searcher = my_cluster.content.searchIndex vm = searcher.FindByIp(ip=vmIP, vmSearch=True) print("VM Config Details for " + vmIP) print(vm.config.name) print(vm.config.guestFullName) # Disconnect from cluster or host connect.Disconnect(my_cluster)
def CollectESX(frameworkInterface,esxHost,esxPort,name,password): Logger = frameworkInterface.Logger if False == LoadSuccessful: Logger.error("esxHost Collector requires the pyvmomi library. (https://github.com/vmware/pyvmomi) - pip install pyvmomi") return False esxPort = int(esxPort) try: myConnection = connect.ConnectNoSSL(esxHost, esxPort, name, password) except Exception as Ex: Logger.error("esxHost Collector unable to login to {0} : {1}".format(esxHost,str(Ex))) atexit.register(Disconnect, myConnection) content = myConnection.RetrieveContent() perfManager = content.perfManager SleepTime = float(frameworkInterface.Interval)/1000.0 try: for datacenter in content.rootFolder.childEntity: if hasattr(datacenter.vmFolder, 'childEntity'): hostFolder = datacenter.hostFolder computeResourceList = hostFolder.childEntity server = computeResourceList[0] break #for server in computeResourceList: hostInfo = GetHostInfo(server) for entry in hostInfo: if not frameworkInterface.DoesCollectorExist(entry): # Do we already have this ID? frameworkInterface.AddCollector(entry) # Nope, so go add it frameworkInterface.SetCollectorValue(entry,hostInfo[entry]) while not frameworkInterface.KillThreadSignalled(): cpuUsage = GetCPU_Util(server,perfManager) if None != cpuUsage: for entry in cpuUsage: if not frameworkInterface.DoesCollectorExist(entry): # Do we already have this ID? frameworkInterface.AddCollector(entry) # Nope, so go add it frameworkInterface.SetCollectorValue(entry,cpuUsage[entry]) time.sleep(SleepTime) except Exception as ex: Logger.error("Unrecoverable error in esxHost Collector plugin: " + str(ex))
def load_hosts(request, host=None): if request.method == "POST": print( "########################################################################################" ) name = request.POST.get("domain") host = request.POST.get("host") user_name = request.POST.get("username") password = request.POST.get("password") si = service_instance = connect.ConnectNoSSL(host=host, user=user_name, pwd=password, port="443") print(si.content) print( "########################################################################################" ) return render(request, "vcenter_hosts.html")
def get(self, id): # Get correct power reading connection = connect.ConnectNoSSL("192.168.182.132", 443, "root", "toasterddos") cursor.execute("SELECT `name` FROM `vms` WHERE `id`='" + str(id) + "'") vm = getVM(connection.content, cursor.fetchone()["name"]) cursor.execute("UPDATE `vms` SET `power`='" + str(vm.runtime.powerState) + "' WHERE `id`='" + str(id) + "'") connect.Disconnect(connection) cursor.execute("SELECT * FROM `vms` WHERE `id`='" + str(id) + "'") vms = cursor.fetchall() for vm in vms: if (id == vm["id"]): return vm, 200 return "VM not found.", 404
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) ########################################### # Get CSC 1.1 information: search VMs # by network(s), for each foun # get informations. # Note: unable to find network informmation # on the vm, like ip address ########################################### dataStore = content.rootFolder.childEntity for data in dataStore: vm = data.vmFolder.childEntity for virtual in vm: # print("Hosts: ", virtual.summary) ##################################################################################### # CIS 8.2.1 to 8.2.5 ##################################################################################### print("Name: " + virtual.config.name) ##################################################################################### # CIS 8.2.6 and 8.2.7- connectable.allowGuestControl ##################################################################################### print("Vm num: ", virtual.config.hardware) # print("Summary: " , virtual.summary.config) stores = data.datastore
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) print(content.userDirectory.RetrieveUserGroups(searchStr='', exactMatch=False, findUsers=True, findGroups=False))
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) ########################################### # Get CSC 1.1 information: search VMs # by network(s), for each foun # get informations. # Note: unable to find network informmation # on the vm, like ip address ########################################### dataStore = content.rootFolder.childEntity for data in dataStore: vm = data.vmFolder.childEntity for virtual in vm: # print("Hosts: ", virtual.summary) ##################################################################################### # CIS 8.6.1 - look for backing-diskMode ##################################################################################### device = virtual.config.hardware.device # print(device) for devices in device: if ("Hard disk" in devices.deviceInfo.label): print(devices)
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) ########################################### # Get CSC 1.1 information: search VMs # by network(s), for each foun # get informations. # Note: unable to find network informmation # on the vm, like ip address ########################################### dataStore = content.rootFolder.childEntity for data in dataStore: vmFolder = data.hostFolder.childEntity for dataVm in vmFolder: host = dataVm.host for h in host: storage = h.config.storageDevice.hostBusAdapter chap = storage[3] ##################################################################################### # CIS 6.1 ##################################################################################### print(chap.authenticationProperties) print(chap)
def __init__(self): try: self.hostname = g.config['cloud_provider']['vmware']['hostname'] self.username = g.config['cloud_provider']['vmware']['username'] self.password = g.config['cloud_provider']['vmware']['password'] self.port = g.config['cloud_provider']['vmware'].get('port', 443) except KeyError: msg = ("Config file doesn't have values related to vmware Cloud" " Provider.") g.log.error(msg) raise exceptions.ConfigError(msg) # Connect vsphere client try: self.vsphere_client = connect.ConnectNoSSL(self.hostname, self.port, self.username, self.password) except Exception as e: g.log.error(e) raise exceptions.CloudProviderError(e)
def ConnectVcenter(): print(" ") passone = "one" passtwo = "two" global answerjson global vcenterpassword vCenterHost = input("Enter vCenter IP or Hostname [{0}]: ".format( answerjson['vcenter'])) vCenterHost = recordAnswer(vCenterHost, "vcenter") vCenterUsername = input("Enter vCenter username [{0}]: ".format( answerjson['vcenteruser'])) vCenterUsername = recordAnswer(vCenterUsername, "vcenteruser") while passone != passtwo: passone = getpass.getpass('Enter vCenter Password: '******'Re-Enter vCenter Password: ') if passone != passtwo: print("Passwords do not match") connection = connect.ConnectNoSSL(vCenterHost, 443, vCenterUsername, passone) vcenterpassword = passone return connection
if job['environment'] == 'kVMware' and origclusterid == clusterid: print("looking for exclusions in job: %s..." % job['name']) parentId = job['parentSourceId'] # get source info (vCenter) parentSource = api( 'get', 'protectionSources?allUnderHierarchy=true&excludeTypes=kResourcePool&id=%s&includeEntityPermissionInfo=true&includeVMFolders=true' % parentId)[0] if excludePoweredOff is True: vcentername = parentSource['protectionSource'][ 'vmWareProtectionSource']['name'] vcenter = connect.ConnectNoSSL(vcentername, 443, vcuser, vpassword) if vcenter: searcher = vcenter.content.searchIndex else: print("Failed to connect to vcenter!") exit(1) # gather list of VMs and parent/child relationships nodes = [] parents = [] nodeParents = {} getnodes(parentSource) # apply VM exclusion rules for sourceId in job['sourceIds']: for node in nodes:
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) ########################################### # Get CSC 1.1 information: search VMs # by network(s), for each foun # get informations. # Note: unable to find network informmation # on the vm, like ip address ########################################### dataStore = content.rootFolder.childEntity for data in dataStore: vmDatastore = data.datastore for d in vmDatastore: print(d.name) browser = d.browser.datastore for h in browser: print(h.vm) for v in h.vm: print(v.name + "/" + v.name + ".vmx") info = v.environmentBrowser.datastoreBrowser infoSearch = info.Search(datastorePath="[datastore1]" + v.name) infoFile = infoSearch.info # infoSearch.SetTaskState(state = "running") # infoSearch.SetTaskState(state = "success") ##################################################################################### # CIS 8.1.1 ##################################################################################### print("Entity: ", infoFile.entityName) print("State: ", infoFile.state) infoFileResult = infoFile.result # print(infoFileResult) for vmxFile in infoFileResult.file: vmxFileInfo = vmxFile # print(vmxFileInfo) if (vmxFile.path == v.name + ".vmx"): print(vmxFile) ##################################################################################### # CIS 8.1.2 ##################################################################################### maxConnections = v.config.maxMksConnections print(v.name + " Max connections: ", maxConnections) # print(content.taskManager) dVm = d.browser.Search( datastorePath="[datastore1] Ubuntu3/Ubuntu3.vmxpcs")
def connect(): from pyVim import connect esx_vcenter = connect.ConnectNoSSL(esx_vcenter_host, 443, esx_vcenter_user, esx_vcenter_pass) return esx_vcenter
from pyVim import connect import sys my_cluster = connect.ConnectNoSSL(sys.argv[1], 443, sys.argv[2], sys.argv[3]) searcher = my_cluster.content.searchIndex vm = searcher.FindByIp(ip=sys.argv[4], vmSearch=True) print vm.config.name connect.Disconnect(my_cluster)
def __init__(self, host, user, pwd): self.si = connect.ConnectNoSSL(host=host, user=user, pwd=pwd) self.content = self.si.RetrieveContent() datacenter = self.content.rootFolder.childEntity[0] self.datacentername = datacenter.name print(self.datacentername)
def main(): """ Simple command-line program for listing the virtual machines on a host. """ args = setup_args() si = None try: si = connect.ConnectNoSSL(host=args.host, user=args.user, pwd=args.password, port=int(args.port)) atexit.register(Disconnect, si) print("No SSL Connection: warning!!") except vim.fault.InvalidLogin: raise SystemExit("Unable to connect to host " "with supplied credentials.") content = si.RetrieveContent() # print(vim.ServiceInstance.RetrieveContent(si)) ########################################### # Get CSC 1.1 information: search VMs # by network(s), for each foun # get informations. # Note: unable to find network informmation # on the vm, like ip address ########################################### dataStore = content.rootFolder.childEntity print(content.about) for data in dataStore: net = data.network for network in net: print(network.summary) print(network.vm) vm = network.vm print(network.host) for virtual in vm: # print("Hosts: ", virtual.summary) print("Vm num: ", virtual.summary.vm) print("Name: ", virtual.summary.config.name) print("Path: ", virtual.summary.config.vmPathName) print("UUID: ", virtual.summary.config.uuid) stores = data.datastore for datas in stores: datasNames = datas.info print(datasNames) print("name:", datasNames.name) print("url: ", datasNames.url) print("UUID: ", datasNames.vmfs.uuid) print("Capacity: ", datasNames.vmfs.capacity) hostSystem = sys.argv[2] print(hostSystem) # tryView = content.viewManager # vmView = tryView.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) # vmObj = [virtMach for virtMach in vmView.view] hostView = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True) obj = [host for host in hostView.view] hostView.Destroy() hostPgDict = {} for host in obj: pgs = host.config.network.portgroup # for i in pgs: # print(i) print("host {} done.".format(host.name)) for s in pgs: switch = s.vswitch # print("prova2", switch) ##################################################################################### # CIS 7.1 # CIS 7.2 # CIS 7.3 ##################################################################################### print("prova2", s.computedPolicy) key = s.key port = [p.mac for p in s.port] ##################################################################################### # CIS 7.4 # CIS 7.5 (partial: document needed) # CIS 7.6 (partial: VGT needed) ##################################################################################### print("VLANID:", s.spec.vlanId) print("KEY: {} ->".format(key)), print("SWITCH: {} ->".format(switch)), print("MAC: {}".format(port)) # for p in port: # print("KEY: {} ->".format(key)), # print("SWITCH: {} ->".format(switch)), # print("MAC: {}".format(p.mac)) newSwitch = host.config.network.vnic dns = host.config.network.dnsConfig print("################") print("DNS") print("################") print("HostName {} ->".format(dns.hostName)), print("DomainName {} ->".format(dns.domainName)), print("DHCP {} ->".format(dns.dhcp)), print("DNS IP {} ->".format(dns.address)), print("vNIC {}".format(dns.virtualNicDevice))
def refresh_virtual_machines(vcenter: ClusterVCenter, force=False): config = settings.PLUGINS_CONFIG['netbox_vcenter'] vcenter_cache_key = get_cache_key(vcenter) # Check whether this server has failed recently and shouldn't be retried yet try: cached_data = cache.get(vcenter_cache_key) if not force and cached_data == 'FAILED': logger.info( "Skipping vCenter update; server {} failed recently".format( vcenter.server)) return if not force: logger.info( "Skipping vCenter update; server {} already in cache".format( vcenter.server)) return cached_data except CacheMiss: pass service_instance = None try: logger.debug("Fetching VMs from {}".format(vcenter.server)) # Connect to the vCenter server if vcenter.validate_certificate: service_instance = connect.Connect(vcenter.server, user=vcenter.username, pwd=vcenter.password) else: service_instance = connect.ConnectNoSSL(vcenter.server, user=vcenter.username, pwd=vcenter.password) content = service_instance.RetrieveContent() vms = get_objects_of_type(content, vim.VirtualMachine) all_stats = {'timestamp': time.time(), 'vms': {}} dvs_cache = {} portgroup_cache = {} for vm in vms: vm_stats = { 'power': None, 'vcpus': None, 'memory': None, 'disk': None, 'nics': [], } try: if vm.runtime.powerState: vm_stats[ 'powered_on'] = vm.runtime.powerState == 'poweredOn' if vm.config.hardware.numCPU: vm_stats['vcpus'] = vm.config.hardware.numCPU if vm.config.hardware.memoryMB: vm_stats['memory'] = vm.config.hardware.memoryMB disk_devices = [ device for device in vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualDisk) ] if disk_devices: # Sum and convert from KB to GB total_capacity = 0 for device in disk_devices: total_capacity += device.capacityInKB vm_stats['disk'] = round(total_capacity / 1048576) for dev in vm.config.hardware.device: if isinstance(dev, vim.vm.device.VirtualEthernetCard): vlan = get_nic_vlan(content, dvs_cache, portgroup_cache, vm, dev) vm_stats['nics'].append({ 'label': dev.deviceInfo.label, 'mac_address': dev.macAddress, 'vlan': vlan, }) except Exception: logger.exception( "Error while fetching virtual machine {} from {}".format( vm.name, vcenter.server)) continue # Collect all stats for returning all_stats['vms'][vm.name] = vm_stats # Cache a list of all VMs cache.set(vcenter_cache_key, all_stats, config['CACHE_TIMEOUT']) return all_stats except Exception: # Set a cookie in the cache so we don't keep retrying logger.exception("Error while fetching virtual machines from {}. " "Disabling checks for 5 minutes.".format( vcenter.server)) cache.set(vcenter_cache_key, 'FAILED', config['CACHE_FAILURE_TIMEOUT']) finally: if service_instance: connect.Disconnect(service_instance)
from pyVim import connect my_host = connect.ConnectNoSSL("192.168.20.219", 443, "domain1\kumar", "kuma@123") searcher = my_host.content.searchIndex vm = searcher.FindbyIp
#!/usr/bin python3 import pyVim from pyVim import connect my_cluster = connect.ConnectNoSSL("192.168.100.9", 443, "amckenzie", "Excellent123$") searcher = my_cluster.content.searchIndex vm = searcher.FindByIp(ip="192.168.100.141", vmSearch=True) print(my_cluster.PortGroup) connect.Disconnect(my_cluster) exit(0)