Giter Site home page Giter Site logo

pyvmomi's Introduction

pyvmomi

downloads py-version

pyVmomi is the Python SDK for the VMware vSphere Management API that allows you to rapidly build solutions integrated with VMware ESXi and vCenter Server. For accessing features from the vSphere Automation APIs (REST), please refer to the VMware vSphere Automation SDK for Python.

Getting Started

To get started, see the getting started guide. You'll need Python, pip, and the samples project.

Installing

The master is code that is in development, official releases are tagged and posted to pypi

  • The official release is available using pip, just run pip install --upgrade pyvmomi.
  • To install the version in github use python setup.py develop for development install or python setup.py install.
  • To install github's version with sso support, just run pip install -e ".[sso]" inside project's home folder.

Testing

Unit tests can be invoked by using the tox command. You may have to configure multiple python interpreters so that you can test in all the environments listed in tox.ini or you will have to run tox with the -e flag to run only in your version of python. For example, if you only have Python 2.7 then tox -e py27 will limit your test run to Python 2.7.

Contributing

Documentation

For general language neutral documentation of vSphere Management API see:

Python Support

  • pyVmomi supports Python 3.4+

Versioning

pyVmomi: X.Y.Z.U.P

vCenter-related: X.Y - (Major release), Z - (Update release), U - (Patch)

pyVmomi-related: P - (pyVmomi patches)

Compatibility Policy

pyVmomi maintains minimum backward compatibility with the previous four releases of vSphere and it's own previous four releases. Compatibility with much older versions may continue to work but will not be actively supported.

For example, version v6.0.0 is most compatible with vSphere 6.0, 5.5, 5.1 and 5.0. Initial releases compatible with a version of vSphere will bare a naked version number of v6.0.0 indicating that version of pyVmomi was released simultaneously with the GA version of vSphere with the same version number.

Support

For official support, users with 'Active - Premium SDK Support, Standard SDK Support, Premier/Success 360, and VMware Select Support can reach out to VMware Global Support for any issues in line with our SDK and API Support policy. For community support, please open a Github issue or start a Discussion.

Related Projects

Have fun!

pyvmomi's People

Contributors

appsalar avatar bhagatp10 avatar esc avatar frankcroth avatar hartsock avatar higebu avatar jeking3 avatar jlhasson avatar joshk0 avatar kevin1024 avatar kumahesh avatar m9e avatar magianxd avatar michaelrice avatar mmattioli avatar mstagi avatar nlamirault avatar nmadhok avatar parthgala avatar patricklundquist avatar pdellaert avatar pgbidkar avatar rgerganov avatar slw07g avatar stacybrock avatar stefanhristov-broadcom avatar stunes avatar tianhao64 avatar tsugliani avatar userlocalhost avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyvmomi's Issues

Malformed Faults fail in non-informative ways

Malformed Faults fail in non-informative ways. Example: LicenseUsageFaults will emit the following SOAP envelope. This envelope will not properly map onto the ServerFaultCode data type inside pyVmomi. The result is that the message will not map onto the appropriate fault type.

<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope 
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <soapenv:Fault>
      <faultcode>ServerFaultCode</faultcode>
      <faultstring/>
      <detail>
        <LicenseUsageFaultFault xsi:type="LicenseUsageFault">
           <reason>dataTampered</reason></LicenseUsageFaultFault>
      </detail>
    </soapenv:Fault>
   </soapenv:Body>
</soapenv:Envelope>

Sometimes the API will return no data for specific properties even though it should

I wrote a python program to query the vm.guest.net property so I could get all of the MAC addresses for all VM's. Most of the time, the program will return the correct results, however, sometimes the program will return nothing for vm.guest.net, yet the VM has not changed in any way. If I restart vCenter, the program will again return all of the correct data.

I have seen this same behavior with other properties but vm.guest.net seems to be the most prone to failure.

To test this, you can write a program to record all of the MAC's for each VM in the infrastructure and you will find over the course of a month one or more of those calls will return nothing.

Thanks, I hope this was clear and you can fix the bug.

Best,

Dave

Poweron task and answer VM question

How could you add code to monitor and answer VM question at VM startup ("has this VM been copied or moved?") while at the same time using WaitForTasks(task, si) function to monitor Poweron task?

unable to connect to vcenter server struct at " Smartconnect step "

/disk1/pyvmomi-community-samples/samples$ python
I am unable to connect vcenter server below python shell struct at Smartconnect step only

I verified firewall status also

root@devstack:/disk1/pyvmomi-community-samples/samples# sudo ufw status
Status: inactive

Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import pyVmomi
from pyVim.connect import SmartConnect
si = SmartConnect(user='root', pwd='xxxx', host='10.67.xx17')
^CTraceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/pyVim/connect.py", line 575, in SmartConnect
preferredApiVersions)
File "/usr/local/lib/python2.7/dist-packages/pyVim/connect.py", line 518, in FindSupportedVersion
path)
File "/usr/local/lib/python2.7/dist-packages/pyVim/connect.py", line 432, in __GetServiceVersionDescription
with closing(urllib.urlopen(url)) as sock:
File "/usr/lib/python2.7/urllib.py", line 86, in urlopen
return opener.open(url)
File "/usr/lib/python2.7/urllib.py", line 207, in open
return getattr(self, name)(url)
File "/usr/lib/python2.7/urllib.py", line 436, in open_https
h.endheaders(data)
File "/usr/lib/python2.7/httplib.py", line 954, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 814, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 776, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1161, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 143, in __init

self.do_handshake()
File "/usr/lib/python2.7/ssl.py", line 305, in do_handshake
self._sslobj.do_handshake()
KeyboardInterrupt

Performance issue ?

Hi There,
I am trying to pull the vswitch/networks/vms data from vcenter. But looks like it took 84 seconds to pull these data:
hostlist = []
for child in datacenter.hostFolder.childEntity:
for host in child.host:
hostlist.append (host)
for host in hostlist:
retdict = {}
retdict['hostname'] = host.name
retdict['connectionState'] = host.runtime.connectionState
retdict['virtualNicList'] = vniclist = []
print 'pull vnic...'
for vnic in
host.configManager.networkSystem.networkConfig.vnic:
# some actions here.
retdict['physicalNicList'] = pniclist = []
print 'pull pnic...'
for pnic in
host.configManager.networkSystem.networkConfig.pnic:
#some actions here
print 'pull vswitches...'
for vswitch in
host.configManager.networkSystem.networkInfo.vswitch:
#some actions here
print 'pull dvs...'
for dvs in
host.configManager.networkSystem.networkInfo.proxySwitch:
#some actions here
print 'pull networks...'
for network in host.network:
#some actions here
print 'pull vm...'
for vm in host.vm:
#some actions here

Is any method to improve the performance of these pull actions ?

Thanks very much!

Add PCI device to VM

Appreciate any help on this, given below is what I am trying. But backing.deviceId I'm not able fetch properly.

        pcispec = vim.vm.device.VirtualDeviceSpec()
        pcispec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
        pcispec.device = vim.vm.device.VirtualPCIPassthrough()
        pcispec.device.key = -1

        pcispec.device.backing = vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
        pcispec.device.backing.id = '00:00.0'
        pcispec.device.backing.deviceId = ??? (HostPciDevice.deviceId)
        #pcispec.device.backing.systemId =  ???

        pcispec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
        pcispec.device.connectable.startConnected = True
        pcispec.device.connectable.allowGuestControl = True

getallvms.py fails if vm inventory uses folders

This patch fixes the issue for the few vCenters we have at my work. I am unable to test these changes on vCenters inventories that don't use folders.

diff --git a/sample/getallvms.py b/sample/getallvms.py
index 2e663b4..823f2d0 100644
--- a/sample/getallvms.py
+++ b/sample/getallvms.py
@@ -39,6 +39,20 @@ def GetArgs():
    args = parser.parse_args()
    return args

+def check_vmobj(vmobj, folder=""):
+    ''' Iterate through vmobj folders until leaf nodes are found, then print their summary.
+        Possible problem:  Can an object have both childEntity and summary?
+    '''
+    try:
+        if vmobj.childEntity:
+            folder = "/".join([folder, vmobj.name])
+            header = "Getting vm list in folder %s:" % folder
+            print header
+            print "=" * len(header)
+            for vm in vmobj.childEntity:
+                check_vmobj(vm, folder)
+    except AttributeError:
+        PrintVmInfo(vmobj)

 def PrintVmInfo(vm):
    """
@@ -87,7 +101,8 @@ def main():
       vmFolder = datacenter.vmFolder
       vmList = vmFolder.childEntity
       for vm in vmList:
-         PrintVmInfo(vm)
+          check_vmobj(vm)
+      #   PrintVmInfo(vm)
    except vmodl.MethodFault, e:
       print "Caught vmodl fault : " + e.msg
       return -1

pep8 branch

Can someone create a pep 8 branch so that we can start sending over some pep 8 stuff? See issue #40 for details.

login to guest example

I'm looking for an example on how to use pyvmomi to login to the guest.

As i understand i should be possible if the guest has vmwaretools installed.

Thanks.

Problem in assigning network for NIC

I have already asked the question here vmware/pyvmomi-community-samples#9

HI,

host.network returns me a list of available networks on the particular host out of which some are standard and some dvs .

Now with this networks when I am adding or editing NICs I am facing problem for dvs networks. If I right click and see the network settings I find the network label is not getting selected. Where as for standard networks the NIC network label is getting selected.

I have tried to change nicspec.device.backing.network = get_obj(content, [vim.Network], net_name) to nicspec.device.backing.network = get_obj(content, [vim.dvs.DistributedVirtualPortgroup], net_name) . But no luck !

What I am doing is given below :

    nicspec = vim.vm.device.VirtualDeviceSpec()
    nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nicspec.device = vim.vm.device.VirtualVmxnet3()
    nicspec.device.wakeOnLanEnabled = True
    nicspec.device.deviceInfo = vim.Description()
    nicspec.device.deviceInfo.label = net_name
    nicspec.device.deviceInfo.summary = net_name             
    nicspec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nicspec.device.backing.network = get_obj(content, [vim.Network], net_name)
    #self.logger.debug ("Assigning network %s for NIC" % net_name)
    nicspec.device.backing.deviceName = net_name
    nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nicspec.device.connectable.startConnected = True
    nicspec.device.connectable.allowGuestControl = True

70b397a2-e0d1-11e3-86cd-42d628adf11a

How do I get the vminfo quicker.

We have around 1500 VM's perc vCenter and around 10vCenter's globally.

To get the particular VM info, I am doing this and it is taking really a long time.

container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
for c in container.view:
if c.name == name:
yourvm = c
break
return yourvm

.......
Retrieving the info from the object like before
print yourvm.runtime.powerState()
.......and more info

Is there anyway to hit the vm directly and get the info without traversing exhaustively ?

Serialize to JSON?

Hi,

I was wondering whether it is possible to serialize an object properties to JSON?

For example taking the following code snippet, how could I dump the vm.summary properties to JSON?

>>> from pyVim.connect import SmartConnect, Disconnect
>>> si = SmartConnect(host='vc01', user='root', pwd='password')
>>> datacenter = content.rootFolder.childEntity[0]
>>> vmFolder = datacenter.vmFolder
>>> vmList = vmFolder.childEntity
>>> vm = vmList[1].childEntity[1]
>>> vm
'vim.VirtualMachine:vm-182'
>>> vm.summary

Having a JSON serializer would really make things simple and easier to integrate with other systems.

Is this possible using pyVmomi?

Thanks and regards,
Marin

vim.fault.InvalidState

When getting events, I always start getting this error after a while:

(vim.fault.InvalidState) {
dynamicType = ,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'The operation is not allowed in the current state.',
faultCause = ,
faultMessage = (vmodl.LocalizableMessage) []
}

Anyone know what this means and how to fix it?

PerfManager Performance

I've been writing an application that pulls a very solid number of metrics from vCenter using the native refreshRate for intervalID (and the other requirements to use the RealtimeStats).

I'm executing single QueryPerf call

results += pm.QueryPerf([x for x in list(group) if x != None])

And then looking at the output:

def build_datasets_from_results(results):
    all_data = {}
    for entity_result in results:

        logger.debug("Processing result from entity: %s" % entity_result.entity.name)

        trash,timestamp = entity_result.sampleInfoCSV.split(',')
        if not all_data.has_key(timestamp): all_data[timestamp] = []
        for result in entity_result.value:
            counterId = result.id.counterId
            counterInfo = [x for x in allCounters if x.key == counterId][0]
            combined_name = ".".join([counterInfo.groupInfo.key, counterInfo.nameInfo.key, result.id.instance]).rstrip('.')
            value = result.value
            all_data[timestamp].append({'entity':entity_result.entity.name, 'metric':combined_name,'value':value})
            logger.debug("Entity %s:%s = %s" % (entity_result.entity.name,combined_name, value) )
    return all_data

I'm finding that this is notably slower than I'd expect, so I did some profiling, and was floored to see that I'm doing approx. 1 call / metric to httplib:

Tue Apr  8 12:00:19 2014    perf.profile

         10434482 function calls (10317291 primitive calls) in 14.715 seconds

   Ordered by: cumulative time
   List reduced from 1590 to 10 due to restriction <10>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.006    0.006   14.715   14.715 tests.py:1(<module>)
        1    0.000    0.000   14.512   14.512 utils/__init__.py:140(collect_and_write_data)
     3012    0.007    0.000   13.033    0.004 /usr/local/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py:552(<lambda>)
     3012    0.019    0.000   13.026    0.004 /usr/local/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py:343(_InvokeMethod)
     3012    0.072    0.000   12.909    0.004 /usr/local/lib/python2.7/site-packages/pyVmomi/SoapAdapter.py:1193(InvokeMethod)
     2957    0.006    0.000   10.257    0.003 /usr/local/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py:545(__call__)
     2957    0.011    0.000   10.251    0.003 /usr/local/lib/python2.7/site-packages/pyVmomi/VmomiSupport.py:369(_InvokeAccessor)
     2957    0.067    0.000   10.240    0.003 /usr/local/lib/python2.7/site-packages/pyVmomi/StubAdapterAccessorImpl.py:29(InvokeAccessor)
        1    0.112    0.112    9.827    9.827 utils/__init__.py:195(build_datasets_from_results)
     3013    0.021    0.000    6.693    0.002 /usr/local/lib/python2.7/httplib.py:1009(getresponse)

Am I doing something wrong here in how I'm capturing these metrics?

raise exceptions

At present actions that seem like they would throw exceptions do not. Instead the error is transmitted as part of a data object and the programmer is expected to check for an exception before proceeding.

Example:

   for vm in vmList:
       if vm.name in vmnames:
           if vm.runtime.powerState != vim.VirtualMachinePowerState.poweredOn:
              task = vm.PowerOn()
              WaitForTasks([task], si)
           lease = vm.ExportVm()
           if lease.error:
                raise lease.error

... this is currently anticipated behavior, so most programmers who have been using the lib for a number of years will have code built to handle this kind of check. The problem is new programmers will expect the method to actually raise an exception (the method's documentation states that it raises exceptions when in pyVmomi it never does).

Enhancement

When an exception occurs on a remote method, raise the exception as if it occurred in Python. This is the most pythonic way to handle raising an exception.

Compatible with vCSA 5.5?

A few weeks ago, I started testing pyvmomi against our vCSA 5.0 server, and it worked great for this simple test script:

https://gist.github.com/anderiv/82467e6755a98d3dbe47

Fast forward to today, I've since upgraded to vCSA (5.5.0.10100 Build 1750781), and am now getting the following when I try to run this script:

Caught exception : 'vim.Folder' object has no attribute 'vmFolder'

I haven't seen anything that suggested that there were any API changes from 5.0 to 5.5 that would cause this. Can you offer any suggestions?

Provided detailed help usage options

When running the samples without any arguments, it does not provide much details on the name of arguments required.

lamw:/git/pyvmomi(master○) » python sample/poweronvm.py
No virtual machine specified for poweron
lamw:
/git/pyvmomi(master○) » python sample/poweronvm.py --help
No virtual machine specified for poweron
lamw:~/git/pyvmomi(master○) » python sample/poweronvm.py -h
Usage: poweronvm.py [options]

poweronvm.py: error: -h option requires an argument

Samples from vSphere SDK for Perl or rbvmomi all provide detailed usage similar to the one below which are very helpful for new users and even existing

vicfg-dns --help
Synopsis: /usr/local/bin/esxcfg-dns OPTIONS

Command-specific options:
--dhcp
-H
"The option (yes | no) to allow or disallow the use of DHCP."
--dns
-D
"The DNS server to be set (IPv6 address valid for vSphere 4.0 and later)."
--domain
-d
"The domain name to be set."
--hostname
-n
"The hostname to be set."
--refresh
-r
Refresh the network system.
--vihost
-h
"The host to use when connecting via a vCenter Server."
--vnic
-V
"The virtual nic adapter to use to override the system DNS (required for --dhcp yes)"

Add Unit Testing

I will feel better about modifications to this library once I start to see unit testing and integration testing suites for this software.

This is probably best done as a series of small commits. Each one adding some tests. This should also probably occur in a branch and then later be merged.

static classes for vim.* and vmodl.* (or use static proxies and python-skeletons)

For better support of IDE and other static code analysis tools it would best to have static classes with decorators to reference. This makes documentation, testing, and other tasks much easier as well. It should be possible to modify the dynamic class generators to decorate a set of static classes to match the vSphere API.

This is a big task and should not be attempted until higher priority and more critical issues are tackled.

pyVmomi should never extend base or core types

This VmomiSupport.py#L179 is considered extremely bad form in the Python community. Extension of core types ties the code to interpreter internals that may not be intended for exposure. This is akin to using a hidden API and should be avoided or at least isolated so that potential damage is easier to control.

Rewrite the code so that the class Link is not needed anymore or so that Link can operate without directly extending a core type.

Adding virtual machine to VLAN

I'm working on automating mass-cloning of a virtual machine from a template for testing purposes. Currently, the only network-related stuff my code creates is an adaptermap to a new static ip address for the cloned virtual machine. I've been looking through the docs, but can't quite seem to figure out how to add it to a VLAN on a switch. My current thought process is that the VirtualEthernetCardDistributedVirtualPortBackingInfo has to be updated in the ConfigSpec used for cloning, but I'm not quite sure what info should be changed, or to propagate it back to the server. Any help would be appreciated.

pyVmomi should never use 'print'

https://docs.python.org/2/library/warnings.html

pyVmomi is a deep level library and it should avoid making use of logging or printing features directly which are application elements we should leave 100% in control of the end application developer.

To close this issue:

  • remove all use of 'print'
  • introduce use of warnings to replace 'print'
  • introduce verbose logging of SOAP messages

Clone a template example

Do you have any examples or docs on using the Clone() function, specifically how to clone/deploy a VM from a template?

Querying datastore cluster fails

Hi
I am trying to get the details of the datastore cluster from vcenter. It works perfectly with RbVMomi but somehow PyVmomi does not properly recognize the StoragePod object.
In Ruby example, in datastoreFolder there is StoragePod("group-p52") which is an instance of StoragePod.
In python there is vim.Folder:group-p52 which is an instance of vim.Folder and does not respond to podStorageDrsEntry.
Any ideas?

Equivalent code samples:

RUBY:

irb(main):002:0> require 'rbvmomi'
=> true
irb(main):003:0> require 'pp'
=> false
irb(main):004:0> params = {:host => '*******',
irb(main):005:1*            :insecure => true,
irb(main):006:1*            :user => 'root',
irb(main):007:1*     :rev=>"5.5",
irb(main):008:1*            :password => '*****'}
=> OMITTED FOR BREVITY
irb(main):009:0> client = RbVmomi::VIM.connect(params)
=> OMITTED FOR BREVITY
irb(main):010:0> dc = client.serviceInstance.find_datacenter
=> Datacenter("datacenter-21")
irb(main):011:0> 
irb(main):012:0*   pp dc.datastoreFolder.childEntity
[StoragePod("group-p52"),
 Datastore("datastore-48"),
 Datastore("datastore-50"),
 Datastore("datastore-49"),
 Datastore("datastore-31"),
 Datastore("datastore-38"),
 Datastore("datastore-40"),
 Datastore("datastore-36"),
 Datastore("datastore-32")]
=> OMITTED FOR BREVITY
irb(main):013:0> pp dc.datastoreFolder.childEntity[0].class
StoragePod
=> StoragePod
irb(main):014:0> pp dc.datastoreFolder.childEntity[0].podStorageDrsEntry
PodStorageDrsEntry(
  actionHistory: [],
  drsFault: [],
  dynamicProperty: [],
  recommendation: [],
  storageDrsConfig: StorageDrsConfigInfo(
    dynamicProperty: [],
    podConfig: StorageDrsPodConfigInfo(
      defaultIntraVmAffinity: true,
      defaultVmBehavior: "automated",
      dynamicProperty: [],
      enabled: true,
      ioLoadBalanceConfig: StorageDrsIoLoadBalanceConfig(
        dynamicProperty: [],
        ioLatencyThreshold: 10,
        ioLoadImbalanceThreshold: 5
      ),
      ioLoadBalanceEnabled: true,
      loadBalanceInterval: 480,
      option: [],
      rule: [],
      spaceLoadBalanceConfig: StorageDrsSpaceLoadBalanceConfig(
        dynamicProperty: [],
        minSpaceUtilizationDifference: 5,
        spaceUtilizationThreshold: 60
      )
    ),
    vmConfig: []
  )
)

PYTHON:

>>> from pyVim import connect
>>> 
>>> si = connect.Connect('***',443,'root','***')
>>> datacenter = si.content.rootFolder.childEntity[0]
>>> datacenter.datastoreFolder.childEntity
(ManagedObject) [
   'vim.Folder:group-p52',
   'vim.Datastore:datastore-48',
   'vim.Datastore:datastore-50',
   'vim.Datastore:datastore-49',
   'vim.Datastore:datastore-31',
   'vim.Datastore:datastore-38',
   'vim.Datastore:datastore-40',
   'vim.Datastore:datastore-36',
   'vim.Datastore:datastore-32'
]
>>> datacenter.datastoreFolder.childEntity[0].__class__.__name__
'vim.Folder'
>>> datacenter.datastoreFolder.childEntity[0].podStorageDrsEntry
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'vim.Folder' object has no attribute 'podStorageDrsEntry'

Set Affinity rule on a particular VM to stop DRS

Hi guys,

I'm writing a python code to Set Affinity rule on a particular VM to stop DRS. I am taking help from Steve Jin's DrsAffRule.java .

I am doing something like :

affinityspec = vim.cluster.AffinityRuleSpec()
affinityspec.name = "My Affinity Group"
affinityspec.enabled = True
affinityspec.vm(my_vm)

The equivalent Java Code I found :

    ClusterAffinityRuleSpec cars = new ClusterAffinityRuleSpec();
    cars.setName("App and DB Appliance Bundle");
    cars.setEnabled(Boolean.TRUE);
    ManagedObjectReference vm1 = createMOR("VirtualMachine", vm1_oid);
    ManagedObjectReference vm2 = createMOR("VirtualMachine", vm2_oid);
    cars.setVm(new ManagedObjectReference[] {vm1, vm2});

Now the problem is affinityspec.vm() takes the MOR of VM . Any idea how do I write a createMOR() function ???

  • Reuben

self._pc.RetrieveContents([filterSpec])[0].propSet[0].val IndexError: list index out of range

Hello,

When trying to get config.hardware.device on a virtualmachine, I run into this error. Any idea how to fix it or whats causing it?

Here's the traceback (virtualMachine is a virtual machine object):
File "vCenter.py", line 126, in init
self.sync()
File "vCenter.py", line 260, in sync
allData = self.getVirtualizationHosts()
File "vCenter.py", line 245, in getVirtualizationHosts
hostProperties["virtualmachines"] = self.getVirtualMachines(host)
File "vCenter.py", line 146, in getVirtualMachines
devices = virtualMachine.config.hardware.device
File "/Library/Python/2.7/site-packages/pyVmomi/VmomiSupport.py", line 547, in call
return self.f(_args, *_kwargs)
File "/Library/Python/2.7/site-packages/pyVmomi/VmomiSupport.py", line 370, in _InvokeAccessor
return self._stub.InvokeAccessor(self, info)
File "/Library/Python/2.7/site-packages/pyVmomi/StubAdapterAccessorImpl.py", line 41, in InvokeAccessor
return self._pc.RetrieveContents([filterSpec])[0].propSet[0].val
IndexError: list index out of range

Thanks,
Harrison

Keep Alive sessions?

Hi,

How can we have a Keep-Alive session to a vSphere host using pyvmomi?

Thanks,
Marin

Enhance CLI option to prompt for Password

It's nice to be able to specify server, username & password on the command-line for ease of use. However, it would be great to also have the ability to prompt for username and especially password so it's not in plaintext and logged on a system.

All other CLI/SDKs provide similar capably, we should look at enhancing our examples as well as the community for this best practice

VLAN ID for VMs

Is there an easy way to get the VLAN ID for a virtual machine?

python 3.4 compatability

Running pip install pyvmomi in a python3 environment:

$ pip install pyvmomi
Downloading/unpacking pyvmomi
  Downloading pyvmomi-5.5.0.tar.gz (156Kb): 156Kb downloaded
  Storing download in cache at /Users/hartsocks/.pip/cache/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2Fp%2Fpyvmomi%2Fpyvmomi-5.5.0.tar.gz
  Running setup.py egg_info for package pyvmomi

Installing collected packages: pyvmomi
  Running setup.py install for pyvmomi
      File "/Users/hartsocks/.venv/pyvmomi-tools-py3/lib/python3.4/site-packages/pyVim/connect.py", line 230
        except ValueError, ve:
                         ^
    SyntaxError: invalid syntax

      File "/Users/hartsocks/.venv/pyvmomi-tools-py3/lib/python3.4/site-packages/pyVmomi/DynamicTypeManagerHelper.py", line 48
        except vmodl.fault.MethodNotFound, err:
                                         ^
    SyntaxError: invalid syntax

      File "/Users/hartsocks/.venv/pyvmomi-tools-py3/lib/python3.4/site-packages/pyVmomi/Iso8601.py", line 179
        except Exception, e:
                        ^
    SyntaxError: invalid syntax

This should not happen.

Session timeouts cause PropertyCollector to return empty data

Sessions that time out and then invoke a method on the vim.PropertyCollector object class can appear to execute the method without error and yield erroneous empty data. This makes it difficult for developers on working on products with long-running processes to distinguish between a session timeout error and a legitimate 'None' response from the server.

We need a fix for this issue that can properly handle session timeouts and we need this fixed by the next release.

Import ova

Request an example script on how to import an ova into vsphere cluster host.

Documentation

Where I can find documentation on how to use this library?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.