1

嗨,我是 python 新手,我正在探索 pyvmomi。在这里我想获取 vm 信息。就像我有一个数据中心,即“DataCenter1”在那个数据中心有两个文件夹 LinuxServer 和 WindowsServer 这些文件夹包含 vms。所以我想用它们各自的文件夹名称获取 vm 名称

    DataCenter1
    |
    |----LinuxServer
    |    |---RHEL-VM
    |    |---Ubuntu-VM
    |
    |----WindowsServer
    |    |---win2k12r2-VM
    |    |---win2k8r2-VM

我的代码:

    from pyvim.connect import SmartConnect, Disconnect
    import ssl

    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    context.verify_mode = ssl.CERT_NONE
    connect = SmartConnect(host="172.0.0.0",user="root",pwd="****",port=int("443"),sslContext=context)

    datacenter = connect.content.rootFolder.childEntity[0]
    print (datacenter)
    vms = datacenter.vmFolder.childEntity
    for i in vms:
        print(i.name)
        #Here I want to fetch vm name and their respective folder names
    Disconnect(c)

在这里,我可以获取所有 vm 名称,但我想获取各个 vm 的文件夹名称。有什么方法吗?你能指导我吗?

4

2 回答 2

3

在这里,您将获得该虚拟机的父名称,即您的文件夹名称(如果存在)。

from pyvim.connect import SmartConnect, Disconnect
import ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
connect = SmartConnect(host="172.0.0.0",user="root",pwd="****",port=int("443"),sslContext=context)

datacenter = connect.content.rootFolder.childEntity[0]
print (datacenter)
vms = datacenter.vmFolder.childEntity
for vm in vms:
    print(vm.parent.name)
Disconnect(c)
于 2016-06-24T06:57:08.800 回答
1

我使用python3.6,下面的完整示例。它实现登录vsphere并打印每个虚拟机名称。

#!/usr/bin/env python3.6
# encoding: utf-8

from pyVim import connect
import ssl


def login():
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    ssl_context.verify_mode = ssl.CERT_NONE
    si = connect.SmartConnect(host='192.168.0.1', user='root', pwd='password',
                              sslContext=ssl_context)
    print(si)
    print('\nHello World!\n')
    print('If you got here, you authenticted into vCenter.')
    data_center = si.content.rootFolder.childEntity[0]
    vms = data_center.vmFolder.childEntity
    for vm in vms:
        print(vm.name)


if __name__ == '__main__':
    login()

结果:

'vim.ServiceInstance:ServiceInstance'

Hello World!

If you got here, you authenticted into vCenter.
sclautoesxd12v03
sclautoesxd12v04
sclautoesxd12v07
sclautoesxd12v09
sclautoesxd12v11
sclautoesxd12v12
sclautoesxd12v13
sclautoesxd12v16
sclautoesxd12v17
sclautoesxd12v01
sclautoesxd12v02
sclautoesxd12v05
sclautoesxd12v06
sclautoesxd12v08
sclautoesxd12v10
sclautoesxd12v14
sclautoesxd12v15
于 2017-07-21T06:50:34.640 回答