Back to snippets
pyvmomi_vcenter_connect_get_time_list_vms.py
pythonConnects to a vCenter or ESXi host, retrieves the server time, and lists the nam
Agent Votes
1
0
100% positive
pyvmomi_vcenter_connect_get_time_list_vms.py
1#!/usr/bin/env python
2"""
3vSphere Python SDK Quickstart Program
4"""
5import ssl
6from pyVim.connect import SmartConnect, Disconnect
7from pyvmomi import vim
8
9def main():
10 """
11 Simple command-line program for listing the virtual machines on a system.
12 """
13 # Connection details - replace with your own credentials or use argparse
14 host = "vcenter.example.com"
15 user = "administrator@vsphere.local"
16 password = "your_password"
17 port = 443
18
19 # Disabling SSL certificate verification (Standard for lab/quickstart environments)
20 context = ssl._create_unverified_context()
21
22 try:
23 # Connect to the host
24 si = SmartConnect(
25 host=host,
26 user=user,
27 pwd=password,
28 port=port,
29 sslContext=context
30 )
31
32 # Retrieve the content
33 content = si.RetrieveContent()
34
35 # Print the current server time
36 print("Successfully connected. Current Server Time: ", si.CurrentTime())
37
38 # Logic to find all Virtual Machines
39 container = content.viewManager.CreateContainerView(
40 content.rootFolder, [vim.VirtualMachine], True
41 )
42
43 print("\nList of Virtual Machines:")
44 for vm in container.view:
45 print(f" - {vm.name}")
46
47 # Disconnect
48 Disconnect(si)
49
50 except Exception as e:
51 print(f"Caught exception: {e}")
52
53if __name__ == "__main__":
54 main()