VMware Vcenter_API

介绍

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

安装:

pip install pyvmomi
pip install pyVim

自己总结的调用API:

# -*- 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())

vmware_vcenter_api的更多相关文章

随机推荐

  1. HTML5知识点汇总(1)

    HTML5 1.html5是什么 万维网的核心语言.标准通用标记语言下的一个应用超文本标记语言(HTML)的第五次重大修改.-------h5并不是一门新的语言,而是html语言的第五次修订. 2.h ...

  2. python3安装crypto出错,及解决方法

    首先我用的python3.5的版本 问题的由来,我想通过python去实现RSA加密算法时,破解某网站的js加密认证,网上说需要安装pycrypto,我就去进行pip安装了 pip install p ...

  3. 关于Modelsim SE软件Fatal License Error的解决方法

    操作环境:Win7 32位系统 软件版本:Modelsim SE 10.1a Modelsim SE软件有时会弹出如图1所示“Fatal License Error”的提示信息,原因可能是软件破解不彻 ...

  4. 【转】numpy教程

    [转载说明] 本来没有必要转载的,只是网上的版本排版不是太好,看的不舒服.所以转过来,重新排版,便于自己查看. 基础篇 NumPy的主要对象是同种元素的多维数组. 这是一个所有的元素都是一种类型.通过 ...

  5. 【转载】COM 组件设计与应用(十六)——连接点(vc.net)

    原文:http://vckbase.com/index.php/wv/1257.html 一.前言 上回书介绍了回调接口,在此基础上,我们理解连接点就容易多了. 二.原理 图一.连接点组件原理图.左侧 ...

  6. [CQOI2012]组装 贪心

    [CQOI2012]组装 贪心好题. LG传送门 首先有一个必须要能推的式子:设第\(i\)种零件选的生产车间位置为\(x _ i\),组装车间位置为\(x\), 则总的花费为 \[f(x) = \s ...

  7. 【JUC源码解析】Phaser

    简介 Phaser,阶段器,可作为一个可复用的同步屏障,与CyclicBarrier和CountDownLatch类似,但更强大. 全览图 如上图所示,phaser,支持phaser树(图中,简化为p ...

  8. 查找linux镜像源中的软件版本并进行安装

    输入以下代码进行软件查找 sudo apt-cache search YourSoftwareName 根据所得到的结果进行安装 sudo apt-get install YourSoftwareNa ...

  9. SAO Utils – SAO风格启动菜单

    SAO Utils 是一款拥有 SAO(刀剑神域)外观风格的启动器,搭载各种各样强大的小工具. 随时随地.在屏幕任何地方 按住鼠标左键和右键并向下拖动 即可呼出应用启动菜单(触控设备直接支持双指下滑手 ...

  10. SQLMAP学习笔记2 Mysql数据库注入

    SQLMAP学习笔记2 Mysql数据库注入 注入流程 (如果网站需要登录,就要用到cookie信息,通过F12开发者工具获取cookie信息) sqlmap -u "URL" - ...