vmware_vcenter_api

Wesley13
• 阅读 741

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())
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
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
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Stella981 Stella981
3年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Easter79 Easter79
3年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这