Context: When Excel and Manual Clicking Become a Nightmare
Imagine this scenario: It’s 2 AM, and your boss texts asking for a configuration list of over 300 virtual machines for an 8 AM audit. If you sit there clicking every single VM on the vSphere Client to copy-paste data, you’ll waste at least 3 hours on meaningless work (even if managing vCenter via smartphone makes it slightly more convenient). With a large system consisting of 8 ESXi hosts and hundreds of VMs, manual work is not only slow but also extremely prone to error.
Many sysadmins typically use PowerCLI on Windows. However, if you are working on Linux or want to integrate reports into an automated dashboard, pyVmomi (the VMware SDK for Python) is a much better choice. This tool allows you to turn complex administrative tasks into reusable code, much like automating VMware vSphere with Terraform. This tool allows you to turn complex administrative tasks into reusable code.
Automating your inventory helps you completely eliminate data entry errors. Instead of pulling an all-nighter, it takes only about 5 seconds to run a Python script and receive a report detailed down to every MAC address.
Installation: Preparing the Tools
To get started, you need Python 3.8 or higher. Do not install libraries directly into your system environment. Use virtualenv to keep your environment clean and avoid version conflicts.
# Initialize virtual environment
python3 -m venv venv-vmware
source venv-vmware/bin/activate
# Install pyVmomi library
pip install pyvmomi
The pyvmomi library is the official toolkit from VMware for communicating with the vCenter API. If you want to export professional CSV reports, you can also install pandas, but Python’s default csv library is sufficient for basic needs.
Implementation: Writing the Resource Scanning Script
A common hurdle when first using pyVmomi is the SSL certificate error (Certificate Verify Failed). This happens because vCenter often uses self-signed certificates. You can eliminate ‘Not Secure’ warnings by configuring proper certificates, but for scripts, we will handle this issue right in the connection setup.
1. Setting Up the vCenter Connection
First, we initialize the connection via ServiceInstance. This is the single entry point for accessing all infrastructure data.
import ssl
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
# Bypass SSL verification for internal certs
s = ssl._create_unverified_context()
def connect_vcenter(host, user, password):
try:
si = SmartConnect(host=host, user=user, pwd=password, sslContext=s)
return si
except Exception as e:
print(f"Connection error: {e}")
return None
2. Extracting Virtual Machine Data
vCenter manages objects in an Inventory Tree structure. We will use CreateContainerView to quickly retrieve a list of all virtual machines without having to manually traverse every folder.
def get_all_vms(si):
content = si.RetrieveContent()
container = content.viewManager.CreateContainerView(
content.rootFolder, [vim.VirtualMachine], True
)
vm_data = []
for vm in container.view:
summary = vm.summary
config = vm.config
info = {
"Name": summary.config.name,
"Status": summary.runtime.powerState,
"CPU": config.hardware.numCPU,
"RAM_GB": config.hardware.memoryMB / 1024,
"IP": summary.guest.ipAddress if summary.guest else "N/A",
"OS": config.guestFullName
}
vm_data.append(info)
container.Destroy()
return vm_data
The code above focuses on key parameters: Name, status, CPU, RAM, and IP. Note: If the virtual machine does not have VMware Tools installed, the ipAddress field will return a null value.
3. Exporting to CSV
To ensure your boss can open the file in Excel immediately, let’s convert the data list to CSV format.
import csv
def export_to_csv(data, filename="vcenter_inventory.csv"):
if not data: return
keys = data[0].keys()
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=keys)
writer.writeheader()
writer.writerows(data)
print(f"Report is ready: {filename}")
Pro Tips: Optimizing for Large Systems
When running the script on a large Cluster (over 500 VMs), the method of iterating through each object as shown above will start to show performance bottlenecks. To optimize, you should use PropertyCollector. This mechanism allows for bulk data fetching, reducing scan time from several minutes to just a few seconds.
Security is also extremely important. Never hardcode your vCenter password directly in the code. Use environment variables to protect your login credentials:
export VC_PASSWORD="YourSecretPassword"
python inventory_script.py
Instead of wasting time on repetitive tasks, let Python do the work for you. Combined with the ability to automate VM deployment from templates, you can achieve a high level of operational maturity.
If you encounter a Connection Timed Out error, check Firewall port 443 between the machine running the script and vCenter. Knowing how to master ESXi Firewall with esxcli can help you troubleshoot these connectivity blocks. Good luck with your automation and may you have peaceful on-call nights!

