PYTHON连接VCENTER自动创建和删除虚拟机快照的简单实现

环境:

PYTHON版本和用到的模块

 

实现代码:

import atexit
import argparse
import sys
import time
import ssl

from pyVmomi import vim, vmodl
from pyVim.task import WaitForTask
from pyVim import connect
from pyVim.connect import Disconnect, SmartConnect, GetSi
import datetime


def getvm(content,vimtype,vmnames):
    vmsobj = None
    container = content.viewManager.CreateContainerView(content.rootFolder,vimtype, True)
    for c in container.view:
        if c.name == vmnames:
            vmsobj = c
            break
    return vmsobj


def get_snapshots_by_name_recursively(snapshots, snapname):
    snap_obj = []
    for snapshot in snapshots:
        if snapshot.name == snapname:
            snap_obj.append(snapshot)
        #result = str(snapname) in str(snapshot.name)#如果删除包含指定字符串的快照,注释上面的条件,打开这个
        #if result:
            #snap_obj.append(snapshot)
        else:
            snap_obj = snap_obj + get_snapshots_by_name_recursively(snapshot.childSnapshotList, snapname)
    return snap_obj


def start():
    today = datetime.date.today()
    oneday = datetime.timedelta(days=1)
    yesterday = today - oneday
    todays=str(today)
    yesterdays = str(yesterday)
    #print todays,yesterdays
    hasMemory = False
    quiesce = False
    description="pythonauto"
    cli=None
    context = ssl._create_unverified_context()

    cli = connect.Connect("vcipaddr",443,"username","password",sslContext=context)
    atexit.register(Disconnect, cli)
    print("coning vc")
    content = cli.RetrieveContent()
    myfile = open("vms.txt", 'r')
    for line in myfile:
        cons = line.split()
        vmnames=cons[0]
        cnd=cons[1]
        vmobj = getvm(content,[vim.VirtualMachine],vmnames)
        if not vmobj:
            print("Virtual Machine %s doesn't exists" % vmnames)
        else:
            if str(cnd).strip() == "cnd":
                #yessnapshot_names = vmnames + yesterdays
                yessnapshot_names ="autosss"
                try:
                    snap_obj = get_snapshots_by_name_recursively(vmobj.snapshot.rootSnapshotList, yessnapshot_names)
                    if len(snap_obj) == 1:
                        snap_obj = snap_obj[0].snapshot
                        WaitForTask(snap_obj.RemoveSnapshot_Task(False)) #参数如果为True  则删除此快照下的全部增量快照
                    else:
                        print("No snapshots found with name: %s on VM: %s" % (yessnapshot_names, vmobj.name))
                except Exception:
                    print "No snapshots For Del"
            else:
                print("Donot del history " % vmnames)
            snapshot_names=vmnames+todays+"autosss"
            WaitForTask(vmobj.CreateSnapshot(snapshot_names,description,hasMemory,quiesce))




start()

 

准备快照的虚拟机写在vms.txt上面,如果需求为创建前快照前先需删除前一天的快照,可将虚拟机标记为cnd,中间用空格分开,不用删除的话随意标记

vm1 cnd
vm2 Dcnd
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页