vmware_vcenter_api
生活随笔
收集整理的這篇文章主要介紹了
vmware_vcenter_api
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
VMware Vcenter_API
介紹
本文主要通過調(diào)用Vcenter_API,獲取其中的數(shù)據(jù)中心,集群,主機(jī),網(wǎng)絡(luò),存儲(chǔ),虛擬機(jī)信息。開發(fā)語言 python
- 使用官方sdk pyvmomi
文檔
- 模塊:https://github.com/vmware/pyvmomi
- 例子:https://github.com/vmware/pyvmomi-community-samples
安裝:
pip install pyvmomi pip install pyVim自己總結(jié)的調(diào)用API:
# -*- coding: utf-8 -*- from pyVim import connect from pyVmomi import vim import json class VcenterApi(object):”“”收集Vcenter中數(shù)據(jù)中心,主機(jī)集群,主機(jī),網(wǎng)絡(luò),虛擬機(jī),的信息“”“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.nameprint(self.datacentername)def get_cluster_list(self):"""獲取所有機(jī)器資源使用情況1。CPU2。內(nèi)存3。磁盤:return:"""# 獲取集群視圖objview = self.content.viewManager.CreateContainerView(self.content.rootFolder,[vim.ComputeResource],True)# 獲取集群對(duì)象clusters = objview.view# 銷毀視圖objview.Destroy()redata = []for cluster in clusters:summary = cluster.summarycpuusage = 0memusage = 0vmcount = 0for host in cluster.host:# print "主機(jī)已使用cpu", host.summary.quickStats.overallCpuUsage# print "主機(jī)已使用內(nèi)存", host.summary.quickStats.overallMemoryUsagecpuusage += host.summary.quickStats.overallCpuUsagememusage += host.summary.quickStats.overallMemoryUsagevmcount += len(host.vm)totaldatastore = 0datastorefree = 0for datastore in cluster.datastore:totaldatastore += datastore.summary.capacitydatastorefree += datastore.summary.freeSpace# print("---------------------------------")# print "集群名稱:", cluster.name# print "集群狀態(tài):", summary.overallStatus# print "總主機(jī)數(shù):", summary.numHosts# print "vm數(shù)量:", vmcount# print "cpu顆數(shù):", summary.numCpuCores# print "總cpu:%.2f GHz" % (summary.totalCpu / 1000.0)# print "已使用cpu: %.2f GHz" % (cpuusage / 1000.0)# print "總內(nèi)存:%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0)# print "已使用mem: %.2f GB" % (memusage / 1024.0)# print "總存儲(chǔ): %.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0)# print "可用存儲(chǔ): %.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 redatadef print_vm_info(self, virtual_machine):"""Print information for a particular virtual machine or recurse into afolder with depth protection"""summary = virtual_machine.summaryif summary.guest.ipAddress:returnself.count+=1print "Name : ", summary.config.nameprint "Template : ", summary.config.templateprint "Path : ", summary.config.vmPathNameprint "Guest : ", summary.config.guestFullNameprint "Instance UUID : ", summary.config.instanceUuidprint "Bios UUID : ", summary.config.uuidannotation = summary.config.annotationif annotation:print "Annotation : ", annotationprint("State : ", summary.runtime.powerState)if summary.guest is not None:ip_address = summary.guest.ipAddresstools_version = summary.guest.toolsStatusif 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 = 0container = self.content.rootFolderviewType = [vim.VirtualMachine]recursive = TruecontainerView = self.content.viewManager.CreateContainerView(container, viewType, recursive)children = containerView.viewfor child in children:self.print_vm_info(child)print(self.count)print(len(children))def get_vm_count(self):container = self.content.rootFolderviewType = [vim.VirtualMachine]recursive = TruecontainerView = self.content.viewManager.CreateContainerView(container, viewType, recursive)children = containerView.viewreturn len(children)def get_datacenter_list(self):"""數(shù)據(jù)中心信息:return:"""objview = self.content.viewManager.CreateContainerView(self.content.rootFolder,[vim.ComputeResource],True)# 獲取集群對(duì)象clusters = objview.view# 銷毀視圖objview.Destroy()# cpu總大小cputotal = 0# 使用cpucpuusage = 0memtotal = 0memusage = 0totaldatastore = 0datastorefree = 0numHosts = 0numCpuCores = 0datastore_list = []for cluster in clusters:summary = cluster.summaryfor host in cluster.host:cpuusage += host.summary.quickStats.overallCpuUsagememusage += host.summary.quickStats.overallMemoryUsagefor datastore in cluster.datastore:datastore_list.append(datastore)cputotal += summary.totalCpumemtotal += summary.totalMemorynumHosts += summary.numHostsnumCpuCores += summary.numCpuCores# print("---------------------------------")# print "集群名稱:", cluster.name# print "集群狀態(tài):", summary.overallStatus# print "總主機(jī)數(shù):", summary.numHosts# print "cpu顆數(shù):", summary.numCpuCores# print "總cpu:%.2f GHz" % (summary.totalCpu / 1000.0)# print "已使用cpu: %.2f GHz" % (cpuusage / 1000.0)# print "總內(nèi)存:%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0)# print "已使用mem: %.2f GB" % (memusage / 1024.0)# print "總存儲(chǔ): %.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0)# print "可用存儲(chǔ): %.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.capacitydatastorefree += datastore.summary.freeSpacereturn {"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.viewobjview.Destroy()# 存儲(chǔ)部分# 存儲(chǔ)集群環(huán)境-通過單個(gè)存儲(chǔ)匯總得到存儲(chǔ)集群得容量情況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": "默認(rèn)集群目錄" 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, # 連接狀態(tài)"multiplehostaccess": i.summary.multipleHostAccess, #多臺(tái)主機(jī)連接"maintenancemode": i.summary.maintenanceMode #當(dāng)前維護(hù)模式狀態(tài)}datastore_list.append(datastore_summary)return datastore_listdef get_host_list(self):"""vcenter下物理主機(jī)信息:return:"""objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.HostSystem], True)objs = objview.viewobjview.Destroy()host_list = []for host in objs:"""物理信息"""# 廠商vendor = host.summary.hardware.vendor# 型號(hào)model = host.summary.hardware.modeluuid = host.summary.hardware.uuid# cpu信號(hào)cpumodel = host.summary.hardware.cpuModel# cpu插槽numcpupkgs = host.summary.hardware.numCpuPkgs# cpu核心numcpucores = host.summary.hardware.numCpuCores# 邏輯處理器numcputhreads = host.summary.hardware.numCpuThreads# cpuMhzcpumhz = host.summary.hardware.cpuMhz# cpu總Ghzcpusize ="%.2f GHz" % (host.summary.hardware.cpuMhz * host.summary.hardware.numCpuCores/1000.0)# 使用cpucpuusage = "%.2f GHz" % (host.summary.quickStats.overallCpuUsage/1000.0)# 內(nèi)存大小 Gmemorysize = "%.2f G" % (host.summary.hardware.memorySize / 1024 / 1024 / 1024.0)memusage = "%.2f G" % (host.summary.quickStats.overallMemoryUsage/1024.0)# 運(yùn)行時(shí)間uptime = host.summary.quickStats.uptime"""運(yùn)行狀態(tài)"""# 主機(jī)連接狀態(tài)connectionstate = host.runtime.connectionState# 主機(jī)電源狀態(tài)powerstate = host.runtime.powerState# 主機(jī)是否處于維護(hù)模式inmaintenancemode = host.runtime.inMaintenanceMode"""基礎(chǔ)信息"""name = host.name# EXSI版本fullname = host.summary.config.product.fullName"""關(guān)聯(lián)信息"""clustername = host.parent.namedatacentername = self.datacentername# 多對(duì)多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_listdef get_networkport_group_list(self):objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.Network], True)objs = objview.viewobjview.Destroy()network_list =[]for networkobj in objs:name = networkobj.name# network = networkobj.summary.networkaccessible = networkobj.summary.accessible# 分布式交換機(jī)名稱try:distributedvirtualswitchname = networkobj.config.distributedVirtualSwitch.namekey = networkobj.config.keyvlanid = networkobj.config.defaultPortConfig.vlan.vlanIdtype = "上行鏈路端口組"if not isinstance(vlanid, int):vlanid = "0-4094"type = "分布式端口組"except AttributeError:continuedata = {"name": name,"datacentername": self.datacentername,"key": key,"accessible": accessible,"distributedvirtualswitchname": distributedvirtualswitchname,"vlanid": vlanid,"type": type,}network_list.append(data)return network_listdef get_vm_list(self):objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.VirtualMachine], True)objs = objview.viewobjview.Destroy()vm_list = []allstime = time.time()count=0for vm_machine in objs:count += 1starttime = time.time()# print(count)# 虛擬機(jī)名稱name = vm_machine.name# EXSI主機(jī)host = vm_machine.summary.runtime.host.name"""運(yùn)行狀態(tài)"""# 連接狀態(tài)connectionstate = vm_machine.summary.runtime.connectionState# 電源狀態(tài)powerstate = vm_machine.summary.runtime.powerState"""guest模版-"""# vmwareTools 安裝情況toolsstatus = vm_machine.summary.guest.toolsStatus# 系統(tǒng)內(nèi)hostnamehostname = 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 顆數(shù)numcpu = vm_machine.summary.config.numCpu# 內(nèi)存總大小memtotal= vm_machine.summary.config.memorySizeMB# 網(wǎng)卡數(shù)numethernetcards = vm_machine.summary.config.numEthernetCards# 虛擬磁盤數(shù)量numvirtualdisks = vm_machine.summary.config.numVirtualDisks# 已使用存儲(chǔ)容量storage_usage = "%.2fG" % (vm_machine.summary.storage.committed/1024/1024/1024.0)# cpu使用Mhzcpuusage = vm_machine.summary.quickStats.overallCpuUsage# MBmemusage = vm_machine.summary.quickStats.guestMemoryUsage# 開機(jī)時(shí)間uptime = vm_machine.summary.quickStats.uptimeSeconds# 運(yùn)行狀態(tài)overallstatus = vm_machine.summary.overallStatus# 網(wǎng)絡(luò)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.labelcapacityinkb = disk.capacityInKBvirtualdisk.append({"label": label, "capacityinkb": capacityinkb})except AttributeError:passexcept AttributeError:# print("----------什么都沒有的------------")continue# print virtualdiskvirtualdiskinfo = json.dumps(virtualdisk)# IP信息ipaddress = vm_machine.guest.ipAddressother_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()-starttimeprint "allover---", time.time()-allstimereturn vm_list if __name__ == '__main__':obj = VcenterApi(host='192.168.100.2', user='admin@vsphere.local', pwd='yourpass')print(obj.get_datastore_list())轉(zhuǎn)載于:https://www.cnblogs.com/NoSong/p/9524832.html
總結(jié)
以上是生活随笔為你收集整理的vmware_vcenter_api的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ionic 修改开发工具的配置
- 下一篇: c++静态变量的生存期