VMware vSphere Python SDK

9.0.0.0 · active · verified Sat Apr 11

pyVmomi is the Python SDK for the VMware vSphere Management API, enabling developers to build solutions integrated with VMware ESXi and vCenter Server. It provides Python bindings for several SOAP-based vSphere APIs, including core VIM API and related extensions like ESX Agent Manager and Storage Policy API. While pyVmomi focuses on SOAP APIs, the vSphere Automation SDK for Python is recommended for REST API features. pyVmomi releases often correlate with vSphere major versions and maintain backward compatibility with the previous four vSphere releases and its own previous four releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a vCenter Server, retrieve its content, and list all virtual machines using pyVmomi. It includes common practices like handling SSL contexts and using environment variables for credentials.

import ssl
import os
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim

# Environment variables for credentials and host
VCENTER_HOST = os.environ.get('VCENTER_HOST', 'your_vcenter_ip_or_fqdn')
VCENTER_USER = os.environ.get('VCENTER_USER', 'your_username')
VCENTER_PASS = os.environ.get('VCENTER_PASS', 'your_password')

if VCENTER_HOST == 'your_vcenter_ip_or_fqdn' or VCENTER_USER == 'your_username' or VCENTER_PASS == 'your_password':
    print("Please set VCENTER_HOST, VCENTER_USER, and VCENTER_PASS environment variables or update the script.")
    exit(1)

def main():
    service_instance = None
    context = None

    try:
        # Disable SSL certificate verification for labs/testing. NOT recommended for production.
        context = ssl._create_unverified_context()
        
        print(f"Connecting to vCenter: {VCENTER_HOST}...")
        service_instance = SmartConnect(host=VCENTER_HOST,
                                      user=VCENTER_USER,
                                      pwd=VCENTER_PASS,
                                      sslContext=context)
        
        content = service_instance.RetrieveContent()
        print(f"Connected to vCenter: {content.about.fullName}")

        # Retrieve all virtual machines
        container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
        vms = container.view
        
        print("\nVirtual Machines:")
        if not vms:
            print("No virtual machines found.")
        for vm in vms:
            print(f"  Name: {vm.name}, Power State: {vm.runtime.powerState}")
        
        container.Destroy()

    except Exception as e:
        print(f"Error: {e}")
    finally:
        if service_instance:
            print("Disconnecting from vCenter.")
            Disconnect(service_instance)

if __name__ == '__main__':
    main()

view raw JSON →