获取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)

你可能感兴趣的:(Linux,AWK)