本文主要經過調用Vcenter_API,獲取其中的數據中心,集羣,主機,網絡,存儲,虛擬機信息。
開發語言 pythonpython
文檔ios
安裝:git
pip install pyvmomi pip install pyVim
本身總結的調用API:github
# -*- coding: utf-8 -*- from pyVim import connect from pyVmomi import vim import json class VcenterApi(object): 」「」 收集Vcenter中數據中心,主機集羣,主機,網絡,虛擬機,的信息 「」「 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 get_cluster_list(self): """ 獲取全部機器資源使用狀況 1。CPU 2。內存 3。磁盤 :return: """ # 獲取集羣視圖 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder,[vim.ComputeResource],True) # 獲取集羣對象 clusters = objview.view # 銷燬視圖 objview.Destroy() redata = [] for cluster in clusters: summary = cluster.summary cpuusage = 0 memusage = 0 vmcount = 0 for host in cluster.host: # print "主機已使用cpu", host.summary.quickStats.overallCpuUsage # print "主機已使用內存", host.summary.quickStats.overallMemoryUsage cpuusage += host.summary.quickStats.overallCpuUsage memusage += host.summary.quickStats.overallMemoryUsage vmcount += len(host.vm) totaldatastore = 0 datastorefree = 0 for datastore in cluster.datastore: totaldatastore += datastore.summary.capacity datastorefree += datastore.summary.freeSpace # print("---------------------------------") # print "集羣名稱:", cluster.name # print "集羣狀態:", summary.overallStatus # print "總主機數:", summary.numHosts # print "vm數量:", vmcount # print "cpu顆數:", summary.numCpuCores # print "總cpu:%.2f GHz" % (summary.totalCpu / 1000.0) # print "已使用cpu: %.2f GHz" % (cpuusage / 1000.0) # print "總內存:%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0) # print "已使用mem: %.2f GB" % (memusage / 1024.0) # print "總存儲: %.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0) # print "可用存儲: %.2f T" % (datastorefree / 1024 / 1024 / 1024 / 1024.0) clusterdata = { "clustername": cluster.name, "overallstatus": summary.overallStatus, "numhosts": summary.numHosts, "numcpucores": summary.numCpuCores, "cputotal": "%.2f GHz" % (summary.totalCpu / 1000.0), "cpuusage": "%.2f GHz" % (cpuusage / 1000.0), "memtotal": "%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0), "memusage": "%.2f GB" % (memusage / 1024.0), "totaldatastore": "%.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0), "datastorefree": "%.2f T" % (datastorefree / 1024 / 1024 / 1024 / 1024.0), "vmcount": vmcount, "datacentername": self.datacentername, } redata.append(clusterdata) return redata def print_vm_info(self, virtual_machine): """ Print information for a particular virtual machine or recurse into a folder with depth protection """ summary = virtual_machine.summary if summary.guest.ipAddress: return self.count+=1 print "Name : ", summary.config.name print "Template : ", summary.config.template print "Path : ", summary.config.vmPathName print "Guest : ", summary.config.guestFullName print "Instance UUID : ", summary.config.instanceUuid print "Bios UUID : ", summary.config.uuid annotation = summary.config.annotation if annotation: print "Annotation : ", annotation print("State : ", summary.runtime.powerState) if summary.guest is not None: ip_address = summary.guest.ipAddress tools_version = summary.guest.toolsStatus if tools_version is not None: print("VMware-tools: ", tools_version) else: print("Vmware-tools: None") if ip_address: print("IP : ", ip_address) else: print("IP : None") if summary.runtime.question is not None: print("Question : ", summary.runtime.question.text) print("") def get_all_vm(self): self.count = 0 container = self.content.rootFolder viewType = [vim.VirtualMachine] recursive = True containerView = self.content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view for child in children: self.print_vm_info(child) print(self.count) print(len(children)) def get_vm_count(self): container = self.content.rootFolder viewType = [vim.VirtualMachine] recursive = True containerView = self.content.viewManager.CreateContainerView( container, viewType, recursive) children = containerView.view return len(children) def get_datacenter_list(self): """ 數據中心信息 :return: """ objview = self.content.viewManager.CreateContainerView(self.content.rootFolder,[vim.ComputeResource],True) # 獲取集羣對象 clusters = objview.view # 銷燬視圖 objview.Destroy() # cpu總大小 cputotal = 0 # 使用cpu cpuusage = 0 memtotal = 0 memusage = 0 totaldatastore = 0 datastorefree = 0 numHosts = 0 numCpuCores = 0 datastore_list = [] for cluster in clusters: summary = cluster.summary for host in cluster.host: cpuusage += host.summary.quickStats.overallCpuUsage memusage += host.summary.quickStats.overallMemoryUsage for datastore in cluster.datastore: datastore_list.append(datastore) cputotal += summary.totalCpu memtotal += summary.totalMemory numHosts += summary.numHosts numCpuCores += summary.numCpuCores # print("---------------------------------") # print "集羣名稱:", cluster.name # print "集羣狀態:", summary.overallStatus # print "總主機數:", summary.numHosts # print "cpu顆數:", summary.numCpuCores # print "總cpu:%.2f GHz" % (summary.totalCpu / 1000.0) # print "已使用cpu: %.2f GHz" % (cpuusage / 1000.0) # print "總內存:%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0) # print "已使用mem: %.2f GB" % (memusage / 1024.0) # print "總存儲: %.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0) # print "可用存儲: %.2f T" % (datastoreusage / 1024 / 1024 / 1024 / 1024.0) # clusterdata = {"clustername": cluster.name, # "overallStatus": summary.overallStatus, # "numHosts": summary.numHosts, # "numCpuCores": summary.numCpuCores, # "totalCpu": "%.2f GHz" % (summary.totalCpu / 1000.0), # "cpuusage": "%.2f GHz" % (cpuusage / 1000.0), # "totalMemory": "%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0), # "memusage": "%.2f GB" % (memusage / 1024.0), # "totaldatastore": "%.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0), # "datastoreusage": "%.2f T" % (datastoreusage / 1024 / 1024 / 1024 / 1024.0), # } # redata.append(clusterdata) for datastore in set(datastore_list): totaldatastore += datastore.summary.capacity datastorefree += datastore.summary.freeSpace return { "cputotal": "%.2f GHz" % (cputotal / 1000.0), "cpuusage": "%.2f GHz" % (cpuusage / 1000.0), "memtotal": "%.2f GB" % (memtotal / 1024 / 1024 / 1024.0), "memusage": "%.2f GB" % (memusage / 1024.0), "totaldatastore": "%.2f T" % (totaldatastore/1024/1024/1024/1024.0), "datastorefree": "%.2f T" % (datastorefree/1024/1024/1024/1024.0), "numhosts": numHosts, "numcpucores": numCpuCores, "vmcount": self.get_vm_count(), "datacentername": self.datacentername, } def get_datastore_list(self): objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.Datastore], True) objs = objview.view objview.Destroy() # 存儲部分 # 存儲集羣環境-經過單個存儲彙總獲得存儲集羣得容量狀況 cluster_store_dict = {} datastore_list = [] for i in objs: capacity = "%.2f G" % (i.summary.capacity/1024/1024/1024.0) freespace = "%.2f G" % (i.summary.freeSpace/1024/1024/1024.0) datastore_summary = { "cluster_store_name": "默認集羣目錄" if i.parent.name=="datastore" else i.parent.name, "datacentername": self.datacentername, "datastore": str(i.summary.datastore), "name": i.summary.name, "url": i.summary.url, #惟必定位器 "capacity": capacity, "freespace": freespace, "type": i.summary.type, "accessible": i.summary.accessible, # 鏈接狀態 "multiplehostaccess": i.summary.multipleHostAccess, #多臺主機鏈接 "maintenancemode": i.summary.maintenanceMode #當前維護模式狀態 } datastore_list.append(datastore_summary) return datastore_list def get_host_list(self): """ vcenter下物理主機信息 :return: """ objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.HostSystem], True) objs = objview.view objview.Destroy() host_list = [] for host in objs: """物理信息""" # 廠商 vendor = host.summary.hardware.vendor # 型號 model = host.summary.hardware.model uuid = host.summary.hardware.uuid # cpu信號 cpumodel = host.summary.hardware.cpuModel # cpu插槽 numcpupkgs = host.summary.hardware.numCpuPkgs # cpu核心 numcpucores = host.summary.hardware.numCpuCores # 邏輯處理器 numcputhreads = host.summary.hardware.numCpuThreads # cpuMhz cpumhz = host.summary.hardware.cpuMhz # cpu總Ghz cpusize ="%.2f GHz" % (host.summary.hardware.cpuMhz * host.summary.hardware.numCpuCores/1000.0) # 使用cpu cpuusage = "%.2f GHz" % (host.summary.quickStats.overallCpuUsage/1000.0) # 內存大小 G memorysize = "%.2f G" % (host.summary.hardware.memorySize / 1024 / 1024 / 1024.0) memusage = "%.2f G" % (host.summary.quickStats.overallMemoryUsage/1024.0) # 運行時間 uptime = host.summary.quickStats.uptime """運行狀態""" # 主機鏈接狀態 connectionstate = host.runtime.connectionState # 主機電源狀態 powerstate = host.runtime.powerState # 主機是否處於維護模式 inmaintenancemode = host.runtime.inMaintenanceMode """基礎信息""" name = host.name # EXSI版本 fullname = host.summary.config.product.fullName """關聯信息""" clustername = host.parent.name datacentername = self.datacentername # 多對多 network = [network.name for network in host.network] datastore = [datastore.name for datastore in host.datastore] data = { "name": name, "clustername": clustername, "datacentername": datacentername, "network": network, "datastore": datastore, "connectionstate": connectionstate, "powerstate": powerstate, "inmaintenancemode": inmaintenancemode, "vendor": vendor, "model": model, "uuid": uuid, "cpumodel": cpumodel, "numcpupkgs": numcpupkgs, "numcpucores": numcpucores, "numcputhreads": numcputhreads, "cpumhz": cpumhz, "cpusize": cpusize, "cpuusage": cpuusage, "memorysize": memorysize, "memusage": memusage, "uptime": uptime, } host_list.append(data) return host_list def get_networkport_group_list(self): objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.Network], True) objs = objview.view objview.Destroy() network_list =[] for networkobj in objs: name = networkobj.name # network = networkobj.summary.network accessible = networkobj.summary.accessible # 分佈式交換機名稱 try: distributedvirtualswitchname = networkobj.config.distributedVirtualSwitch.name key = networkobj.config.key vlanid = networkobj.config.defaultPortConfig.vlan.vlanId type = "上行鏈路端口組" if not isinstance(vlanid, int): vlanid = "0-4094" type = "分佈式端口組" except AttributeError: continue data = { "name": name, "datacentername": self.datacentername, "key": key, "accessible": accessible, "distributedvirtualswitchname": distributedvirtualswitchname, "vlanid": vlanid, "type": type, } network_list.append(data) return network_list def get_vm_list(self): objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.VirtualMachine], True) objs = objview.view objview.Destroy() vm_list = [] allstime = time.time() count=0 for vm_machine in objs: count += 1 starttime = time.time() # print(count) # 虛擬機名稱 name = vm_machine.name # EXSI主機 host = vm_machine.summary.runtime.host.name """運行狀態""" # 鏈接狀態 connectionstate = vm_machine.summary.runtime.connectionState # 電源狀態 powerstate = vm_machine.summary.runtime.powerState """guest模版-""" # vmwareTools 安裝狀況 toolsstatus = vm_machine.summary.guest.toolsStatus # 系統內hostname hostname = vm_machine.summary.guest.hostName """config""" uuid = vm_machine.summary.config.uuid # 是否模版 template = vm_machine.summary.config.template # vm文件路徑 vmpathname = vm_machine.summary.config.vmPathName # cpu 顆數 numcpu = vm_machine.summary.config.numCpu # 內存總大小 memtotal= vm_machine.summary.config.memorySizeMB # 網卡數 numethernetcards = vm_machine.summary.config.numEthernetCards # 虛擬磁盤數量 numvirtualdisks = vm_machine.summary.config.numVirtualDisks # 已使用存儲容量 storage_usage = "%.2fG" % (vm_machine.summary.storage.committed/1024/1024/1024.0) # cpu使用Mhz cpuusage = vm_machine.summary.quickStats.overallCpuUsage # MB memusage = vm_machine.summary.quickStats.guestMemoryUsage # 開機時間 uptime = vm_machine.summary.quickStats.uptimeSeconds # 運行狀態 overallstatus = vm_machine.summary.overallStatus # 網絡 network = [i.name for i in vm_machine.network] # 虛擬磁盤信息 virtualdisk = [] try: for disk in vm_machine.config.hardware.device: try: if hasattr(disk, "diskObjectId"): label = disk.deviceInfo.label capacityinkb = disk.capacityInKB virtualdisk.append({"label": label, "capacityinkb": capacityinkb}) except AttributeError: pass except AttributeError: # print("----------什麼都沒有的------------") continue # print virtualdisk virtualdiskinfo = json.dumps(virtualdisk) # IP信息 ipaddress = vm_machine.guest.ipAddress other_ip = set() for vmnet in vm_machine.guest.net: for ip in vmnet.ipAddress: other_ip.add(ip) data = { "name": name, "host": host, "datacentername": self.datacentername, "ipaddress": ipaddress, "other_ip": json.dumps(list(other_ip)), "connectionstate": connectionstate, "powerstate": powerstate, "toolsstatus": toolsstatus, "hostname": hostname, "uuid": uuid, "template": template, "vmpathname": vmpathname, "numcpu": numcpu, "memtotal": memtotal, "numethernetcards": numethernetcards, "numvirtualdisks": numvirtualdisks, "storage_usage": storage_usage, "cpuusage": cpuusage, "memusage": memusage, "uptime": uptime, "overallstatus": overallstatus, "network": network, "virtualdiskinfo": virtualdiskinfo, } vm_list.append(data) # print time.time()-starttime print "allover---", time.time()-allstime return vm_list if __name__ == '__main__': obj = VcenterApi(host='192.168.100.2', user='admin@vsphere.local', pwd='yourpass') print(obj.get_datastore_list())