from pyVim.connect import SmartConnect
from pyVmomi import vim
import ssl
import json
def collect_vm_hardware(vm_obj):
hardware_list = []
try:
if vm_obj.config and hasattr(vm_obj.config.hardware, 'device'):
for hw in vm_obj.config.hardware.device:
if hasattr(hw.deviceInfo, 'label'):
hardware_list.append(hw.deviceInfo.label)
else:
hardware_list.append('Unidentified Hardware')
except Exception as error:
print(f'Error processing {vm_obj.name}: {error}')
return hardware_list
def fetch_vcenter_data():
vc_host = 'vcenter.example.com'
vc_user = 'administrator@vsphere.local'
vc_pass = 'secure_password'
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
try:
service = SmartConnect(
host=vc_host,
user=vc_user,
pwd=vc_pass,
sslContext=ssl_context
)
content = service.RetrieveContent()
host_view = content.viewManager.CreateContainerView(
content.rootFolder,
[vim.HostSystem],
True
)
inventory = []
for esxi_host in host_view.view:
for virtual_machine in esxi_host.vm:
entry = {
'vm_name': virtual_machine.name,
'host_name': esxi_host.name,
'devices': collect_vm_hardware(virtual_machine)
}
inventory.append(entry)
with open('vm_inventory.json', 'w') as output:
json.dump(inventory, output, indent=2)
except Exception as connection_error:
print(f'Connection failed: {connection_error}')
finally:
if 'service' in locals():
SmartConnect.Disconnect(service)
if __name__ == '__main__':
fetch_vcenter_data()
This implementation connects to a vCenter server and retrieves:
- All ESXi hosts in the inventory
- Virtual machines running on each host
- Hardware devices configured for each VM
The collected data is stored in a JSON file with the following structure:
[
{
"vm_name": "VM1",
"host_name": "esxi01.example.com",
"devices": ["SCSI Controller", "Network Adapter"]
}
]
Key components:
- Uses pyVmomi library for vSphere API interactions
- Implements proper SSL context configuration
- Incldues error handling for connection issues
- Outputs structured JSON data for further processign