獲取esxi主機的內存和CPU使用率

from __future__ import print_function
import atexit
from pyVim.connect import SmartConnectNoSSL, Disconnect
from pyVmomi import vim

memory_and_cpu_dict = {}

def getHostMemoryAndCPU(content):
    memory_dict = {}
    cpu_dict = {}
    for datacenter in content.rootFolder.childEntity:
        hostFolder = datacenter.hostFolder
        for clusterComputeResource in hostFolder.childEntity:
            for computeResource in clusterComputeResource.host:

                host_memory_usage = computeResource.summary.quickStats.overallMemoryUsage    #內存使用量
                host_memory_all = computeResource.summary.hardware.memorySize / 1048576      #內存總量

                host_memory_usage_rate = int((host_memory_usage / host_memory_all) * 100)   #內存使用率
                hostName = computeResource.name
                memory_dict[hostName] = host_memory_usage_rate

                host_cpu_usage = computeResource.summary.quickStats.overallCpuUsage     #CPU使用量
                host_numcpu_cores = computeResource.summary.hardware.numCpuCores        #CPU核數
                host_mhz_per_core = computeResource.summary.hardware.cpuMhz             #CPU赫茲
                host_cpu_all = host_numcpu_cores * host_mhz_per_core                    #CPU總量
                host_cpu_usage_rate = int((host_cpu_usage / host_cpu_all) * 100)        #CPU使用率
                cpu_dict[hostName] = host_cpu_usage_rate

    memory_and_cpu_dict['cpu_uasge'] = cpu_dict
    memory_and_cpu_dict['memory_usage'] = memory_dict
    return memory_and_cpu_dict




def run(host, user, pwd, port):
    """
    Simple command-line program for listing the virtual machines on a host.
    """

    si = None
    try:
        si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=int(port))
        atexit.register(Disconnect, si)
    except vim.fault.InvalidLogin:
        raise SystemExit("Unable to connect to host "
                         "with supplied credentials.")

    content = si.RetrieveContent()
    memory_and_cpu_dict = getHostMemoryAndCPU(content)
    print(memory_and_cpu_dict)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章