VMware Vcenter_API

介绍

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

安装:

  1. pip install pyvmomi
  2. pip install pyVim

自己总结的调用API:

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

vmware_vcenter_api的更多相关文章

随机推荐

  1. 白帽子讲web安全——访问控制

    上一章说的认证与会话管理,这章是访问控制,刚看访问控制这章的时候,感觉跟上章的“授权”没什么区别,第一感受就是“授权”. 之后看了才进一步了解,“授权”是好比屋子的主人进来了,那么他可以坐在客厅,也可 ...

  2. 复制文件到IDE等工具出现乱码解决方案

    首要的解决方案是设置文件或者项目或者工作空间的编码,可以采用在文件上.项目上右键->properties进行设置 第二种方式是在editplus等编辑器里打开文件,然后打开文件之后点击菜单Fil ...

  3. 2017-2018-1 20155318 《信息安全系统设计基础》第九周课下实践——实现mypwd

    2017-2018-1 20155318 <信息安全系统设计基础>第九周课下实践--实现mypwd 相关知识 man -k 查找含有关键字的内容 与管道命令结合使用:man -k k1 | ...

  4. 20145209刘一阳《JAVA程序设计》第七周课堂测试

    第七周课堂测试 1.命令"CREATE DATABASE "用来创建一个数据库.(A) A .true B .false 2.以下不属于驱动的四种类型的是(C) A .JDBC-O ...

  5. Security1:登录和用户

    授予权限的思路,可以用一句话来概括,那就是:授予 Principal 操作 Securable 的 Permission,在多数文档中,把 Principal 翻译为安全主体,Securable翻译为 ...

  6. 改革春风吹满地,安卓新系统Q上线腾讯WeTest

    “刚要适配安卓派,Q就来了.” 3月14日谷歌推出了期待已久的Android Q的首个测试版本Android Q Beta 1 ,这是Android系统推出以来的第十个大版本. 安卓Q相比之前的版本, ...

  7. 封装的一套简单轻量级JS 类库(RapidDevelopmentFramework.JS)

    1.最近好久没有更新自己的博客了,一直在考虑自己应该写一些什么.4.2日从苏州回到南京的路上感觉自己的内心些崩溃和失落,我就不多说了? 猛然之间我认为自己需要找一下内心的平衡.决定开发属于自己一套快速 ...

  8. express的web server设置流程

    对于express的设置,一直是拿来就用,只知其然,今天查了一下文档,记录详细过程如下. 1.实现基本常用功能需要的模块path 用来处理路径字符串拼接,设置模板路径和静态资源路径时使用cookie- ...

  9. Java实现Oracle的to_char函数

    /** * 将int.long.double.float.String.Date等类型format成字符类型 * * 一.数字format格式处理: * 01)99.99的实现,小数位四舍五入不够位数 ...

  10. hdu2544最短路(dijkstra)

    传送门 dijkstra #include<bits/stdc++.h> using namespace std; const int INF=0x3f3f3f3f; ; int dist ...