1. 程式人生 > 實用技巧 >Python 獲取EXSI宿主機上虛擬機器資料

Python 獲取EXSI宿主機上虛擬機器資料

安裝python3.6.8,依賴,一定要安裝,否則後面可能無法安裝一些python外掛
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
yum -y install python36 git
pip3 install --upgrade pip
安裝監控vmware的sdk pyvmomi
git clone https://github.com/vmware/pyvmomi.git
cd pyvmomi/
python3 setup.py install
編寫通過pyvmomi外掛獲取虛擬機器資訊的指令碼
#!/usr/bin/python3
#coding:utf-8

"""
獲取所有的vcenter相關資訊
包括exsi的硬體資源資訊和vmware客戶端的硬體分配資訊
"""
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect, SmartConnectNoSSL
import atexit
import argparse


def get_args():
    parser = argparse.ArgumentParser(
        description='Arguments for talking to vCenter')

    parser.add_argument('-s', '--host',
                        required=True,
                        action='store',
                        help='vSpehre service to connect to')

    parser.add_argument('-o', '--port',
                        type=int,
                        default=443,
                        action='store',
                        help='Port to connect on')

    parser.add_argument('-u', '--user',
                        required=True,
                        action='store',
                        help='User name to use')

    parser.add_argument('-p', '--password',
                        required=True,
                        action='store',
                        help='Password to use')

    args = parser.parse_args()
    return args


def get_obj(content, vimtype, name=None):
    '''
    列表返回,name 可以指定匹配的物件
    '''
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    obj = [ view for view in container.view]
    return obj


def main():
    esxi_host = {}
    args = get_args()
    # connect this thing
    si = SmartConnectNoSSL(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()
    esxi_obj = get_obj(content, [vim.HostSystem])
    for esxi in esxi_obj:
        esxi_host[esxi.name] = {'esxi_info':{},'datastore':{}, 'network': {}, 'vm': {}}

        esxi_host[esxi.name]['esxi_info']['廠商'] = esxi.summary.hardware.vendor
        esxi_host[esxi.name]['esxi_info']['型號'] = esxi.summary.hardware.model
        for i in esxi.summary.hardware.otherIdentifyingInfo:
            if isinstance(i, vim.host.SystemIdentificationInfo):
                esxi_host[esxi.name]['esxi_info']['SN'] = i.identifierValue
        esxi_host[esxi.name]['esxi_info']['處理器'] = '數量:%s 核數:%s 執行緒數:%s 頻率:%s(%s) ' % (esxi.summary.hardware.numCpuPkgs,
                                                                                      esxi.summary.hardware.numCpuCores,
                                                                                      esxi.summary.hardware.numCpuThreads,
                                                                                      esxi.summary.hardware.cpuMhz,
                                                                                      esxi.summary.hardware.cpuModel)
        esxi_host[esxi.name]['esxi_info']['處理器使用率'] = '%.1f%%' % (esxi.summary.quickStats.overallCpuUsage /
                                                       (esxi.summary.hardware.numCpuPkgs * esxi.summary.hardware.numCpuCores * esxi.summary.hardware.cpuMhz) * 100)
        esxi_host[esxi.name]['esxi_info']['記憶體(MB)'] = esxi.summary.hardware.memorySize/1024/1024
        esxi_host[esxi.name]['esxi_info']['可用記憶體(MB)'] = '%.1f MB' % ((esxi.summary.hardware.memorySize/1024/1024) - esxi.summary.quickStats.overallMemoryUsage)
        esxi_host[esxi.name]['esxi_info']['記憶體使用率'] = '%.1f%%' % ((esxi.summary.quickStats.overallMemoryUsage / (esxi.summary.hardware.memorySize/1024/1024)) * 100)
        esxi_host[esxi.name]['esxi_info']['系統'] = esxi.summary.config.product.fullName

        for ds in esxi.datastore:
            esxi_host[esxi.name]['datastore'][ds.name] = {}
            esxi_host[esxi.name]['datastore'][ds.name]['總容量(G)'] = int((ds.summary.capacity)/1024/1024/1024)
            esxi_host[esxi.name]['datastore'][ds.name]['空閒容量(G)'] = int((ds.summary.freeSpace)/1024/1024/1024)
            esxi_host[esxi.name]['datastore'][ds.name]['型別'] = (ds.summary.type)
        for nt in esxi.network:
            esxi_host[esxi.name]['network'][nt.name] = {}
            esxi_host[esxi.name]['network'][nt.name]['標籤ID'] = nt.name
        for vm in esxi.vm:
            esxi_host[esxi.name]['vm'][vm.name] = {}
            esxi_host[esxi.name]['vm'][vm.name]['電源狀態'] = vm.runtime.powerState
            esxi_host[esxi.name]['vm'][vm.name]['CPU(核心總數)'] = vm.config.hardware.numCPU
            esxi_host[esxi.name]['vm'][vm.name]['記憶體(總數MB)'] = vm.config.hardware.memoryMB
            esxi_host[esxi.name]['vm'][vm.name]['系統資訊'] = vm.config.guestFullName
            if vm.guest.ipAddress:
                esxi_host[esxi.name]['vm'][vm.name]['IP'] = vm.guest.ipAddress
            else:
                esxi_host[esxi.name]['vm'][vm.name]['IP'] = '伺服器需要開機後才可以獲取'

            for d in vm.config.hardware.device:
                if isinstance(d, vim.vm.device.VirtualDisk):
                    esxi_host[esxi.name]['vm'][vm.name][d.deviceInfo.label] = str((d.capacityInKB)/1024/1024) + ' GB'

    f = open(args.host + '.txt', 'w')
    for host in esxi_host:
        print('ESXI IP:', host)
        f.write('ESXI IP: %s \n' % host)
        for hd in esxi_host[host]['esxi_info']:
            print('  %s:    %s' % (hd, esxi_host[host]['esxi_info'][hd]))
            f.write('  %s:    %s' % (hd, esxi_host[host]['esxi_info'][hd]))
        for ds in esxi_host[host]['datastore']:
            print('  儲存名稱:', ds)
            f.write('  儲存名稱: %s \n' % ds)
            for k in esxi_host[host]['datastore'][ds]:
                print('       %s:  %s' % (k, esxi_host[host]['datastore'][ds][k]))
                f.write('       %s:  %s \n' % (k, esxi_host[host]['datastore'][ds][k]))
        for nt in esxi_host[host]['network']:
            print('  網路名稱:', nt)
            f.write('  網路名稱:%s \n' % nt)
            for k in esxi_host[host]['network'][nt]:
                print('        %s:  %s' % (k, esxi_host[host]['network'][nt][k]))
                f.write('        %s:  %s \n' % (k, esxi_host[host]['network'][nt][k]))
        for vmachine in esxi_host[host]['vm']:
            print('  虛擬機器名稱:', vmachine)
            f.write('  虛擬機器名稱:%s \n' % vmachine)
            for k in esxi_host[host]['vm'][vmachine]:
                print('        %s:  %s' % (k, esxi_host[host]['vm'][vmachine][k]))
                f.write('        %s:  %s \n' % (k, esxi_host[host]['vm'][vmachine][k]))
    f.close()


if __name__ == '__main__':
    main()

指令碼使用方法:

python3 exsi.py -s 192.168.0.251 -o 443 -u root -p 123456

結果