vmware_vcenter_api

VMware Vcenter_API

介绍

本文主要通过调用Vcenter_API,获取其中的数据中心,集群,主机,网络,存储,虚拟机信息。

安装:

1pip install pyvmomi 2pip install pyVim

自己总结的调用API:

1# -*- coding: utf-8 -*- 2from pyVim import connect 3from pyVmomi import vim 4import json 5class VcenterApi(object): 6 ”“” 7 收集Vcenter中数据中心,主机集群,主机,网络,虚拟机,的信息 8 “”“ 9 def __init__(self, host, user, pwd): 10 self.si = connect.ConnectNoSSL(host=host, user=user, pwd=pwd) 11 self.content = self.si.RetrieveContent() 12 datacenter = self.content.rootFolder.childEntity[0] 13 self.datacentername = datacenter.name 14 print(self.datacentername) 15 16 def get_cluster_list(self): 17 """ 18 获取所有机器资源使用情况 19 1CPU 20 2。内存 21 3。磁盘 22 :return: 23 """ 24 # 获取集群视图 25 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder,[vim.ComputeResource],True) 26 # 获取集群对象 27 clusters = objview.view 28 # 销毁视图 29 objview.Destroy() 30 31 redata = [] 32 for cluster in clusters: 33 summary = cluster.summary 34 35 cpuusage = 0 36 memusage = 0 37 vmcount = 0 38 for host in cluster.host: 39 # print "主机已使用cpu", host.summary.quickStats.overallCpuUsage 40 # print "主机已使用内存", host.summary.quickStats.overallMemoryUsage 41 cpuusage += host.summary.quickStats.overallCpuUsage 42 memusage += host.summary.quickStats.overallMemoryUsage 43 vmcount += len(host.vm) 44 45 46 totaldatastore = 0 47 datastorefree = 0 48 for datastore in cluster.datastore: 49 totaldatastore += datastore.summary.capacity 50 datastorefree += datastore.summary.freeSpace 51 # print("---------------------------------") 52 # print "集群名称:", cluster.name 53 # print "集群状态:", summary.overallStatus 54 # print "总主机数:", summary.numHosts 55 # print "vm数量:", vmcount 56 # print "cpu颗数:", summary.numCpuCores 57 # print "总cpu:%.2f GHz" % (summary.totalCpu / 1000.0) 58 # print "已使用cpu: %.2f GHz" % (cpuusage / 1000.0) 59 # print "总内存:%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0) 60 # print "已使用mem: %.2f GB" % (memusage / 1024.0) 61 # print "总存储: %.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0) 62 # print "可用存储: %.2f T" % (datastorefree / 1024 / 1024 / 1024 / 1024.0) 63 clusterdata = { 64 "clustername": cluster.name, 65 "overallstatus": summary.overallStatus, 66 "numhosts": summary.numHosts, 67 "numcpucores": summary.numCpuCores, 68 "cputotal": "%.2f GHz" % (summary.totalCpu / 1000.0), 69 "cpuusage": "%.2f GHz" % (cpuusage / 1000.0), 70 "memtotal": "%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0), 71 "memusage": "%.2f GB" % (memusage / 1024.0), 72 "totaldatastore": "%.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0), 73 "datastorefree": "%.2f T" % (datastorefree / 1024 / 1024 / 1024 / 1024.0), 74 "vmcount": vmcount, 75 "datacentername": self.datacentername, 76 } 77 redata.append(clusterdata) 78 return redata 79 80 def print_vm_info(self, virtual_machine): 81 """ 82 Print information for a particular virtual machine or recurse into a 83 folder with depth protection 84 """ 85 summary = virtual_machine.summary 86 if summary.guest.ipAddress: 87 return 88 self.count+=1 89 print "Name : ", summary.config.name 90 print "Template : ", summary.config.template 91 print "Path : ", summary.config.vmPathName 92 print "Guest : ", summary.config.guestFullName 93 print "Instance UUID : ", summary.config.instanceUuid 94 print "Bios UUID : ", summary.config.uuid 95 annotation = summary.config.annotation 96 if annotation: 97 print "Annotation : ", annotation 98 print("State : ", summary.runtime.powerState) 99 if summary.guest is not None: 100 ip_address = summary.guest.ipAddress 101 tools_version = summary.guest.toolsStatus 102 if tools_version is not None: 103 print("VMware-tools: ", tools_version) 104 else: 105 print("Vmware-tools: None") 106 if ip_address: 107 print("IP : ", ip_address) 108 else: 109 print("IP : None") 110 if summary.runtime.question is not None: 111 print("Question : ", summary.runtime.question.text) 112 print("") 113 114 def get_all_vm(self): 115 self.count = 0 116 container = self.content.rootFolder 117 viewType = [vim.VirtualMachine] 118 recursive = True 119 containerView = self.content.viewManager.CreateContainerView( 120 container, viewType, recursive) 121 children = containerView.view 122 123 for child in children: 124 125 self.print_vm_info(child) 126 print(self.count) 127 print(len(children)) 128 129 def get_vm_count(self): 130 131 container = self.content.rootFolder 132 viewType = [vim.VirtualMachine] 133 recursive = True 134 containerView = self.content.viewManager.CreateContainerView( 135 container, viewType, recursive) 136 children = containerView.view 137 return len(children) 138 139 def get_datacenter_list(self): 140 """ 141 数据中心信息 142 :return: 143 """ 144 145 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder,[vim.ComputeResource],True) 146 # 获取集群对象 147 clusters = objview.view 148 # 销毁视图 149 objview.Destroy() 150 151 # cpu总大小 152 cputotal = 0 153 # 使用cpu 154 cpuusage = 0 155 memtotal = 0 156 memusage = 0 157 totaldatastore = 0 158 datastorefree = 0 159 numHosts = 0 160 numCpuCores = 0 161 datastore_list = [] 162 163 for cluster in clusters: 164 summary = cluster.summary 165 for host in cluster.host: 166 cpuusage += host.summary.quickStats.overallCpuUsage 167 memusage += host.summary.quickStats.overallMemoryUsage 168 169 for datastore in cluster.datastore: 170 datastore_list.append(datastore) 171 cputotal += summary.totalCpu 172 memtotal += summary.totalMemory 173 numHosts += summary.numHosts 174 numCpuCores += summary.numCpuCores 175 176 # print("---------------------------------") 177 # print "集群名称:", cluster.name 178 # print "集群状态:", summary.overallStatus 179 # print "总主机数:", summary.numHosts 180 # print "cpu颗数:", summary.numCpuCores 181 # print "总cpu:%.2f GHz" % (summary.totalCpu / 1000.0) 182 # print "已使用cpu: %.2f GHz" % (cpuusage / 1000.0) 183 # print "总内存:%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0) 184 # print "已使用mem: %.2f GB" % (memusage / 1024.0) 185 # print "总存储: %.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0) 186 # print "可用存储: %.2f T" % (datastoreusage / 1024 / 1024 / 1024 / 1024.0) 187 # clusterdata = {"clustername": cluster.name, 188 # "overallStatus": summary.overallStatus, 189 # "numHosts": summary.numHosts, 190 # "numCpuCores": summary.numCpuCores, 191 # "totalCpu": "%.2f GHz" % (summary.totalCpu / 1000.0), 192 # "cpuusage": "%.2f GHz" % (cpuusage / 1000.0), 193 # "totalMemory": "%.2f GB" % (summary.totalMemory / 1024 / 1024 / 1024.0), 194 # "memusage": "%.2f GB" % (memusage / 1024.0), 195 # "totaldatastore": "%.2f T" % (totaldatastore / 1024 / 1024 / 1024 / 1024.0), 196 # "datastoreusage": "%.2f T" % (datastoreusage / 1024 / 1024 / 1024 / 1024.0), 197 # } 198 # redata.append(clusterdata) 199 200 201 for datastore in set(datastore_list): 202 totaldatastore += datastore.summary.capacity 203 datastorefree += datastore.summary.freeSpace 204 205 return { 206 "cputotal": "%.2f GHz" % (cputotal / 1000.0), 207 "cpuusage": "%.2f GHz" % (cpuusage / 1000.0), 208 "memtotal": "%.2f GB" % (memtotal / 1024 / 1024 / 1024.0), 209 "memusage": "%.2f GB" % (memusage / 1024.0), 210 "totaldatastore": "%.2f T" % (totaldatastore/1024/1024/1024/1024.0), 211 "datastorefree": "%.2f T" % (datastorefree/1024/1024/1024/1024.0), 212 "numhosts": numHosts, 213 "numcpucores": numCpuCores, 214 "vmcount": self.get_vm_count(), 215 "datacentername": self.datacentername, 216 } 217 218 def get_datastore_list(self): 219 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.Datastore], True) 220 objs = objview.view 221 objview.Destroy() 222 # 存储部分 223 # 存储集群环境-通过单个存储汇总得到存储集群得容量情况 224 cluster_store_dict = {} 225 datastore_list = [] 226 for i in objs: 227 capacity = "%.2f G" % (i.summary.capacity/1024/1024/1024.0) 228 freespace = "%.2f G" % (i.summary.freeSpace/1024/1024/1024.0) 229 datastore_summary = { 230 "cluster_store_name": "默认集群目录" if i.parent.name=="datastore" else i.parent.name, 231 "datacentername": self.datacentername, 232 "datastore": str(i.summary.datastore), 233 "name": i.summary.name, 234 "url": i.summary.url, #唯一定位器 235 "capacity": capacity, 236 "freespace": freespace, 237 "type": i.summary.type, 238 "accessible": i.summary.accessible, # 连接状态 239 "multiplehostaccess": i.summary.multipleHostAccess, #多台主机连接 240 "maintenancemode": i.summary.maintenanceMode #当前维护模式状态 241 } 242 datastore_list.append(datastore_summary) 243 return datastore_list 244 245 def get_host_list(self): 246 """ 247 vcenter下物理主机信息 248 :return: 249 """ 250 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.HostSystem], True) 251 objs = objview.view 252 objview.Destroy() 253 host_list = [] 254 for host in objs: 255 """物理信息""" 256 # 厂商 257 vendor = host.summary.hardware.vendor 258 # 型号 259 model = host.summary.hardware.model 260 uuid = host.summary.hardware.uuid 261 # cpu信号 262 cpumodel = host.summary.hardware.cpuModel 263 # cpu插槽 264 numcpupkgs = host.summary.hardware.numCpuPkgs 265 # cpu核心 266 numcpucores = host.summary.hardware.numCpuCores 267 # 逻辑处理器 268 numcputhreads = host.summary.hardware.numCpuThreads 269 # cpuMhz 270 cpumhz = host.summary.hardware.cpuMhz 271 # cpu总Ghz 272 cpusize ="%.2f GHz" % (host.summary.hardware.cpuMhz * host.summary.hardware.numCpuCores/1000.0) 273 # 使用cpu 274 cpuusage = "%.2f GHz" % (host.summary.quickStats.overallCpuUsage/1000.0) 275 # 内存大小 G 276 memorysize = "%.2f G" % (host.summary.hardware.memorySize / 1024 / 1024 / 1024.0) 277 memusage = "%.2f G" % (host.summary.quickStats.overallMemoryUsage/1024.0) 278 # 运行时间 279 uptime = host.summary.quickStats.uptime 280 281 """运行状态""" 282 # 主机连接状态 283 connectionstate = host.runtime.connectionState 284 # 主机电源状态 285 powerstate = host.runtime.powerState 286 # 主机是否处于维护模式 287 inmaintenancemode = host.runtime.inMaintenanceMode 288 """基础信息""" 289 name = host.name 290 # EXSI版本 291 fullname = host.summary.config.product.fullName 292 """关联信息""" 293 clustername = host.parent.name 294 datacentername = self.datacentername 295 # 多对多 296 network = [network.name for network in host.network] 297 datastore = [datastore.name for datastore in host.datastore] 298 data = { 299 "name": name, 300 "clustername": clustername, 301 "datacentername": datacentername, 302 "network": network, 303 "datastore": datastore, 304 "connectionstate": connectionstate, 305 "powerstate": powerstate, 306 "inmaintenancemode": inmaintenancemode, 307 "vendor": vendor, 308 "model": model, 309 "uuid": uuid, 310 "cpumodel": cpumodel, 311 "numcpupkgs": numcpupkgs, 312 "numcpucores": numcpucores, 313 "numcputhreads": numcputhreads, 314 "cpumhz": cpumhz, 315 "cpusize": cpusize, 316 "cpuusage": cpuusage, 317 "memorysize": memorysize, 318 "memusage": memusage, 319 "uptime": uptime, 320 } 321 322 host_list.append(data) 323 return host_list 324 325 def get_networkport_group_list(self): 326 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.Network], True) 327 objs = objview.view 328 objview.Destroy() 329 network_list =[] 330 for networkobj in objs: 331 name = networkobj.name 332 # network = networkobj.summary.network 333 accessible = networkobj.summary.accessible 334 # 分布式交换机名称 335 try: 336 distributedvirtualswitchname = networkobj.config.distributedVirtualSwitch.name 337 key = networkobj.config.key 338 vlanid = networkobj.config.defaultPortConfig.vlan.vlanId 339 type = "上行链路端口组" 340 if not isinstance(vlanid, int): 341 vlanid = "0-4094" 342 type = "分布式端口组" 343 except AttributeError: 344 continue 345 346 data = { 347 "name": name, 348 "datacentername": self.datacentername, 349 "key": key, 350 "accessible": accessible, 351 "distributedvirtualswitchname": distributedvirtualswitchname, 352 "vlanid": vlanid, 353 "type": type, 354 } 355 network_list.append(data) 356 return network_list 357 358 def get_vm_list(self): 359 objview = self.content.viewManager.CreateContainerView(self.content.rootFolder, [vim.VirtualMachine], True) 360 objs = objview.view 361 objview.Destroy() 362 vm_list = [] 363 allstime = time.time() 364 count=0 365 for vm_machine in objs: 366 count += 1 367 starttime = time.time() 368 # print(count) 369 # 虚拟机名称 370 name = vm_machine.name 371 # EXSI主机 372 host = vm_machine.summary.runtime.host.name 373 """运行状态""" 374 # 连接状态 375 connectionstate = vm_machine.summary.runtime.connectionState 376 # 电源状态 377 powerstate = vm_machine.summary.runtime.powerState 378 """guest模版-""" 379 # vmwareTools 安装情况 380 toolsstatus = vm_machine.summary.guest.toolsStatus 381 # 系统内hostname 382 hostname = vm_machine.summary.guest.hostName 383 384 """config""" 385 uuid = vm_machine.summary.config.uuid 386 # 是否模版 387 template = vm_machine.summary.config.template 388 # vm文件路径 389 vmpathname = vm_machine.summary.config.vmPathName 390 # cpu 颗数 391 numcpu = vm_machine.summary.config.numCpu 392 # 内存总大小 393 memtotal= vm_machine.summary.config.memorySizeMB 394 # 网卡数 395 numethernetcards = vm_machine.summary.config.numEthernetCards 396 # 虚拟磁盘数量 397 numvirtualdisks = vm_machine.summary.config.numVirtualDisks 398 # 已使用存储容量 399 storage_usage = "%.2fG" % (vm_machine.summary.storage.committed/1024/1024/1024.0) 400 # cpu使用Mhz 401 cpuusage = vm_machine.summary.quickStats.overallCpuUsage 402 # MB 403 memusage = vm_machine.summary.quickStats.guestMemoryUsage 404 # 开机时间 405 uptime = vm_machine.summary.quickStats.uptimeSeconds 406 # 运行状态 407 overallstatus = vm_machine.summary.overallStatus 408 # 网络 409 network = [i.name for i in vm_machine.network] 410 # 虚拟磁盘信息 411 virtualdisk = [] 412 try: 413 for disk in vm_machine.config.hardware.device: 414 try: 415 if hasattr(disk, "diskObjectId"): 416 label = disk.deviceInfo.label 417 capacityinkb = disk.capacityInKB 418 virtualdisk.append({"label": label, "capacityinkb": capacityinkb}) 419 except AttributeError: 420 pass 421 except AttributeError: 422 # print("----------什么都没有的------------") 423 continue 424 # print virtualdisk 425 virtualdiskinfo = json.dumps(virtualdisk) 426 427 # IP信息 428 ipaddress = vm_machine.guest.ipAddress 429 other_ip = set() 430 for vmnet in vm_machine.guest.net: 431 for ip in vmnet.ipAddress: 432 other_ip.add(ip) 433 434 data = { 435 "name": name, 436 "host": host, 437 "datacentername": self.datacentername, 438 "ipaddress": ipaddress, 439 "other_ip": json.dumps(list(other_ip)), 440 "connectionstate": connectionstate, 441 "powerstate": powerstate, 442 "toolsstatus": toolsstatus, 443 "hostname": hostname, 444 "uuid": uuid, 445 "template": template, 446 "vmpathname": vmpathname, 447 "numcpu": numcpu, 448 "memtotal": memtotal, 449 "numethernetcards": numethernetcards, 450 "numvirtualdisks": numvirtualdisks, 451 "storage_usage": storage_usage, 452 "cpuusage": cpuusage, 453 "memusage": memusage, 454 "uptime": uptime, 455 "overallstatus": overallstatus, 456 "network": network, 457 "virtualdiskinfo": virtualdiskinfo, 458 } 459 460 vm_list.append(data) 461 # print time.time()-starttime 462 463 print "allover---", time.time()-allstime 464 return vm_list 465if __name__ == '__main__': 466 467 468 obj = VcenterApi(host='192.168.100.2', user='admin@vsphere.local', pwd='yourpass') 469 print(obj.get_datastore_list())
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )