2

So, I am trying to make a Python script using pyvmomi to control the state of a virtual machine I'm running on my ESXi server. Basically, I tried using connection.content.searchIndex.FindByIp(ip="the ip of the VM", vmSearch=True) to grab my VM and then power it on, but of course I cannot get the IP of the VM when it's off. So, I was wondering if there was any way I could get the VM, maybe by name or its ID? I searched around quite a bit but couldn't really find a solution. Either way, here's my code so far:

from pyVim import connect
# Connect to ESXi host
connection = connect.Connect("192.168.182.130", 443, "root", "password")

# Get a searchIndex object
searcher = connection.content.searchIndex

# Find a VM
vm = searcher.FindByIp(ip="192.168.182.134", vmSearch=True)

# Print out vm name
print (vm.config.name)

# Disconnect from cluster or host
connect.Disconnect(connection)
techtoolbox
  • 45
  • 2
  • 6

2 Answers2

2

The searchindex doesn't have any methods to do a 'findbyname' so you'll probably have to resort to pulling back all of VMs and filtering through them client side.

Here's an example of returning all the VMs: https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/getallvms.py

Another option, if you're using vCenter 6.5+, there's the vSphere Automation SDK for Python where you can interact with the REST APIs to do a server side filter. More info: https://github.com/vmware/vsphere-automation-sdk-python

Kyle Ruddy
  • 1,886
  • 1
  • 7
  • 5
2

This code might prove helpful:

from pyVim.connect import SmartConnect
from pyVmomi import vim
import ssl

s=ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s.verify_mode=ssl.CERT_NONE
si= SmartConnect(host="192.168.100.10", user="admin", pwd="admin123",sslContext=s)
content=si.content

def get_all_objs(content, vimtype):
        obj = {}
        container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
        for managed_object_ref in container.view:
                obj.update({managed_object_ref: managed_object_ref.name})
        return obj

vmToScan = [vm for vm in get_all_objs(content,[vim.VirtualMachine]) if "ubuntu-16.04.4" == vm.name]
chb
  • 1,727
  • 7
  • 25
  • 47
  • 1
    Welcome to Stack Overflow. This answer looks like it has some promise, but you neglected to explain the overall effect or purpose of the code you posted. Also, please use the markdown available to you in the editor to format your answers and questions on the site. – chb Jan 06 '19 at 09:34
  • sorry for un-formatted and un-commented code :( I am new to stackoverflow – Snehal Biche Jan 16 '19 at 13:31