简体   繁体   English

通过pyVmomi获取vmId

[英]Get vmId via pyVmomi

Currently Im using vim-cmd to perform multiple operations in my VMware center. 目前我使用vim-cmd在我的VMware中心执行多项操作。

I'm using SSH paramiko module to connect and retrieve vim-cmd command status: 我正在使用SSH paramiko模块来连接和检索vim-cmd命令状态:

vim-cmd vmsvc/getallvms
vim-cmd vmsvc/power.getstate 13
vim-cmd vmsvc/power.on 13
vim-cmd vmsvc/power.off 13
vim-cmd vmsvc/destroy 13

I want to use pyVmomi library to run some commands and for this it is required to provide the vmId identifier: 我想使用pyVmomi库来运行一些命令,为此需要提供vmId标识符:

from pyvim import connect
from pyVmomi import vim
from pyVmomi import vmodl

vim-cmd vmsvc/get.summary 13
Listsummary:

(vim.vm.Summary) {
   dynamicType = <unset>, 
   vm = 'vim.VirtualMachine:13', 

What command can I use to get the vmId ? 我可以使用什么命令来获取vmId

What you are calling the vmid is called a ManagedObjectReference or mor, or a moref (within the context of the vSphere Web services API). 您调用vmid的内容称为ManagedObjectReference或mor,或称为moref(在vSphere Web services API的上下文中)。 With pyVmomi there are a couple of ways to get the moref. 使用pyVmomi有两种方法可以获得moref。 One is to just print the object. 一种是打印对象。 That method will print the moref in a format such that it gives the ManagedObjectType:moref like below. 该方法将以一种格式打印moref,使其提供ManagedObjectType:moref如下所示。 Another way if you just want the actual moref you can access vm._moId. 另一种方法,如果你只想要实际的moref,你可以访问vm._moId。 Below is an example using a Datacenter object. 下面是使用Datacenter对象的示例。

from pyVim.connect import SmartConnect
from pyVmomi import vim
si = SmartConnect(host='10.12.254.137', user='administrator@vsphere.local', pwd='password')
content = si.RetrieveContent()
children = content.rootFolder.childEntity
for child in children:
    print child

'vim.Datacenter:datacenter-33'
'vim.Datacenter:datacenter-2'
children[0].name
'1000110'
dc = vim.Datacenter('datacenter-33')
dc._stub = si._stub
dc.name
'1000110'

If you want to access an Object using its moref then follow the example I provided. 如果要使用moref访问Object,请按照我提供的示例进行操作。 I covered this on my blog here about a year or so ago. 我介绍这个在我的博客在这里大约一年多前。 You might check out that article for a more in depth explanation. 您可以查看该文章以获得更深入的解释。

I've encountered the same thing, 我遇到过同样的事情,
I know it has been a while but I suggest this 我知道已经有一段时间但我建议这样做
hack which works fine for me, I hope you can use it. 黑客对我来说很好,我希望你能用它。

buf = ("%s" % (vm.summary.vm))

which for example gives 例如,给出

vim.VirtualMachine:11

now, we wish to extract the number and for python3 it is recommended using regular expression. 现在,我们希望提取数字,对于python3,建议使用正则表达式。

import re #regular expression
re.findall('\d+', buf)

which result with a list with 1 element 结果列表包含1个元素

'11' '11'
type(buf)<br/>
<class 'list'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM