VMware-ESXI主机信息获取

  • 获取ESXI主机信息
  • 数据中心, Vcenter, 集群, 主机, 品牌, 型号, VMware版本, 状态, Cpu核数, CPU 型号, 内存总数, 内存已使用,序列号
# -*- coding:utf-8 -*-

import os
import datetime
#from datetime import datetime
from configparser import ConfigParser 
import atexit
from pyVmomi import vim, vmodl
from pyVim.connect import SmartConnectNoSSL, Disconnect
import xlwt


def setStyle(name):
    style = xlwt.XFStyle()
    font = xlwt.Font()
    pattern = xlwt.Pattern()
    alignment = xlwt.Alignment()
    font.colour_index = 1  # 字体颜色
    font.name = name  # 字体
    font.bold = True    # 加粗
    alignment.horz = 2   # 对齐方式,居中
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = 23  # 背景颜色
    style.alignment = alignment
    style.pattern = pattern
    style.font = font
    return style


def data_write(filepath, datas):
    f = xlwt.Workbook()
    sheet1 = f.add_sheet(u'宿主机清单', cell_overwrite_ok=True)
    line_01 = ['数据中心', 'Vcenter', '集群', '主机', '品牌', '型号', 'VMware版本', '状态', 'Cpu核数', 'CPU 型号', '内存总数',
               '内存已使用', '序列号']
    for x in range(len(line_01)):
        sheet1.write(0, x, line_01[x], setStyle("宋体"))
    i = 1  # i 值为excel从第几行开始写
    for data in datas:
        for j in range(len(data)):
            sheet1.write(i, j, data[j])
        i = i + 1
    f.save(filepath)


def getStorage(host):
    memoryCount = round((host.hardware.memorySize / 1024 ** 3), 2)
    memoryUsage = round((host.summary.quickStats.overallMemoryUsage / 1024), 2) if host.summary.quickStats.overallMemoryUsage else 0
    #memoryPercent = str(round((memoryUsage / memoryCount), 2)*100) + "%"
    #return memoryCount, memoryUsage, memoryPercent
    return memoryCount, memoryUsage


def hostSummary(dc, vc_ip, cluster, host):
    host_list = []
    host_sn = []
    memoryCount, memoryUsage = getStorage(host)
    host_list.append(dc)
    host_list.append(vc_ip)
    host_list.append(cluster)
    host_list.append(host.name)
    host_list.append(host.hardware.systemInfo.vendor)
    host_list.append(host.hardware.systemInfo.model)
    product = host.config.product.fullName if host.config else 'None'
    host_list.append(product)
    host_list.append(host.summary.overallStatus)
    host_list.append(host.summary.hardware.numCpuThreads)
    host_list.append(host.summary.hardware.cpuModel)
    host_list.append(memoryCount)
    host_list.append(memoryUsage)
   # host_list.append(memoryPercent)
    for summary in host.summary.hardware.otherIdentifyingInfo:
        if summary.identifierType.key == 'ServiceTag':
            host_list.append(summary.identifierValue)
    return host_list

def run(si, vc_address, cfg):
    global vm_lists
    try:
        content = si.RetrieveContent()
        atexit.register(Disconnect, si)
        view = si.content.viewManager.CreateContainerView(si.content.rootFolder, [vim.HostSystem], True)
        hosts = view.view
        view.Destroy()

        for host in hosts:
            dc_name = host.parent.parent.parent.name
            cluster = host.parent.name
            host_info = hostSummary(dc_name, vc_address, cluster, host)
            vm_lists.append(host_info)

        # children = content.rootFolder.childEntity
        # for child in children:
        #     dc = child
        #     dc_name = child.name
        #     clusters = dc.hostFolder.childEntity
        #     for cluster in clusters:
        #         hosts = cluster.host
        #         for host in hosts:
        #             host_info = hostSummary(dc_name, vc_address, cluster.name, host)
        #             vm_lists.append(host_info)
    except vmodl.MethodFault as error:
        print("Caught vmodl fault:" + error.msg)
        return False, error.msg
    return True, "Ok"

if __name__ == "__main__":
    try:
        base_dir = os.path.dirname(os.path.abspath(__file__))
        html_dir = "/var/www/html/prod/"
        virtual_file = os.path.join(html_dir, os.path.join("ESXI", "%s.xlsx" % (datetime.datetime.now().strftime("%Y-%m-%d"))))
        config_file = os.path.join(base_dir, os.path.join("etc", "vSphere.ini"))
        config = ConfigParser()
        config.read(config_file, encoding="utf-8")
        vm_lists = []
        for section in config.sections():
            cfg = dict(config.items(section))
            try:
                si = SmartConnectNoSSL(host=section, port=cfg["port"], user=cfg["user"], pwd=cfg["passwd"])
            except Exception as e:
                print("Login error:" + cfg["info"])
                continue
            else:
                print("Login Success:" + cfg["info"])
                run(si, section, cfg)
        data_write(virtual_file, vm_lists)
        print("宿主机数量:", len(vm_lists))
    except Exception as err:
        print(err)
    exit()

  • 获取的信息如下
数据中心 Vcenter 集群 主机 品牌 型号 VMware版本 状态 Cpu核数 CPU 型号 内存总数 内存已使用 序列号
Transsion-Pre-Prod-DC 10.250.100.160 Transsion-Pre-Prod-Cluster 10.250.100.21 Huawei RH2288H V3 VMware ESXi 6.5.0 build-8294253 green 48 Intel(R) Xeon(R) CPU E5-2650 v4 @ 2.20GHz 511.61 253.71 9QSKBT2
  • vSphere.ini 文件内容
[10.250.x.x]
info = Transsion-TEST
user = administrator@vsphere.local
passwd = xx
port = 443
[10.250.x.x]
info = Transsion-Pre-Prod
user = administrator@vsphere.local
passwd = x
port = 443
posted @ 2021-03-24 11:57  独孤云翔  阅读(1591)  评论(0)    收藏  举报