Search

Introduction to pyVmomi: Python SDKs for VMware vSphere API


pyVmomi and pyVim are the Python SDKs for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter. I thought that this would be a good automation tool up my sleeve and decided to give it a try. There are quite a lot of resources which we can use as a starting point.






You can refer the pyVmomi GitHub page: https://github.com/vmware/pyvmomi . In addition, you can refer to community samples here: http://vmware.github.io/pyvmomi-community-samples/ and reference for vSphere Management API here: https://code.vmware.com/apis/968/vsphere.


Let us get started with exploring this feature. First we start off with pyVmomi and pyVim modules installation:



Now, let us take a look at some of the basic commands:


1- Connecting to a host

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
import ssl
import atexit
import datetime

if __name__ == "__main__":
    context = None
    if hasattr(ssl, '_create_unverified_context'):
        context = ssl._create_unverified_context()

host = '<hostip>'
user = 'root'
password = '<rootpass>'

h = SmartConnect(host=host, user=user, pwd=password, sslContext=context )
print(h)

Output:

Here, the "ssl._create_unverified_context()" is required to ignore invalid certificate error when connecting to the server.


2- Placing the host into maintenance mode:

h = SmartConnect(host=host, user=user, pwd=password, sslContext=context )
print(h)
search= h.content.searchIndex
host= search.FindByIp(ip=host, vmSearch=False)
print(host)
host.EnterMaintenanceMode_Task(0)
Disconnect(h)

3- Exit maintenance mode:

h = SmartConnect(host=host, user=user, pwd=password, sslContext=context )
print(h)
search= h.content.searchIndex
host= search.FindByIp(ip=host, vmSearch=False)
print(host)
host.ExitMaintenanceMode_Task(0)
Disconnect(h)


4- Shutdown Host:

h = SmartConnect(host=host, user=user, pwd=password, sslContext=context )
print(h)
search= h.content.searchIndex
host= search.FindByIp(ip=host, vmSearch=False)
print(host)
host.ShutdownHost_Task(force=True)
Disconnect(h)

The pyVmomi and the pyVim SDKs are very easy and user friendly to use for users who are familiar with the APIs. This is a very useful toolkit of sys admins trying to automate VMware tasks; watch this space for more pyVmomi scripts!

297 views0 comments

Recent Posts

See All