Python: Get Snapshot information

This is a cutout from some code I wrote. This is not tested in its current form, and only published as inspiration on how to get access to snapshot information using the vSphere API for python

def get_all_hosts(si: 'pyVmomi.VmomiSupport.vim.ServiceInstance') -> list:
    hosts = []

    content = si.RetrieveContent()
    subFolders = content.rootFolder.childEntity
    for sf in subFolders:
        children = sf.hostFolder.childEntity
        for computeresource in children:
            if computeresource.__class__.__name__ == "vim.ClusterComputeResource":
                for host in computeresource.host:
                    if host.summary.runtime.connectionState == 'connected':
                        hosts.append(host)
            elif computeresource.__class__.__name__ == 'vim.Folder':
                for folder in computeresource.childEntity:
                    for host in folder.host:
                        if host.summary.runtime.connectionState == 'connected':
                            hosts.append(host)
            else:
                print(f"Skipping: {cluster.name} as it is not a cluster")
                continue

    return hosts

def get_all_vm_snapshots(vm):
    results = []
    try:
        rootSnapshots = vm.snapshot.rootSnapshotList
    except:
        rootSnapshots = []

    for snapshot in rootSnapshots:
        results.append(snapshot)
        results += get_child_snapshots(snapshot)

    return results

def get_child_snapshots(snapshot):
    results = []
    snapshots = snapshot.childSnapshotList

    for snapshot in snapshots:
        results.append(snapshot)
        results += get_child_snapshots(snapshot)

    return results

if __name__ == '__main__':
    from pyVim.connect import SmartConnectNoSSL, Disconnect

    si = SmartConnectNoSSL(host=vcenter, user='username', pwd='password', port=443)
    atexit.register(Disconnect, si)

    hosts = get_all_hosts(si)
    #snapshots = {}
    for host in hosts:
        vms = host.vm
        for vm in vms:
            snapshots = get_all_vm_snapshots(vm)
            if len(snapshots) > 0:
                print(vm.name)
                for snapshot in snapshots:
                    print(f"- {snapshot.name}")

Leave a Reply

Your email address will not be published. Required fields are marked *