用python(pyvmomi)管理vmware ESXi/vCenter-阿里云开发者社区

开发者社区> 开发与运维> 正文

用python(pyvmomi)管理vmware ESXi/vCenter

简介: 自动化运维,用python(pyvmomi)管理vmware ESXi/vCenter

环境

开发环境:Ubuntu 18.04 + python3.7
以下环境经过测试都可以使用:centos 6/7 + python3.4/3.6/3.7windows 7/2016 +python3.4/3.6/3.7

安装必要模块pyvmomi

pip install pyvmomi 

如果是linux系统有pip2和pip3 两个版本,需要使用

pip3 install pyvmomi

代码

host='ESXi 机器ip'
user='root'
password='密码'
port=443#端口
context = None
if hasattr(ssl, '_create_unverified_context'):
    context = ssl._create_unverified_context()
si = SmartConnect(host=host,user=user,pwd=password,port=port,sslContext=context)
if not si:
    print("帐号密码有问题")
atexit.register(Disconnect, si)


###################################################################################################
def WaitForTasks(tasks, si):#任务
    pc = si.content.propertyCollector
    taskList = [str(task) for task in tasks]
    objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks]
    propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,pathSet=[], all=True)
    filterSpec = vmodl.query.PropertyCollector.FilterSpec()
    filterSpec.objectSet = objSpecs
    filterSpec.propSet = [propSpec]
    filter = pc.CreateFilter(filterSpec, True)
    try:
        version, state = None, None
        while len(taskList):
            update = pc.WaitForUpdates(version)
            for filterSet in update.filterSet:
                for objSet in filterSet.objectSet:
                    task = objSet.obj
                    for change in objSet.changeSet:
                        if change.name == 'info':
                            state = change.val.state
                        elif change.name == 'info.state':
                            state = change.val
                        else:
                            continue
                        if not str(task) in taskList:
                            continue
                        if state == vim.TaskInfo.State.success:
                            taskList.remove(str(task))
                        elif state == vim.TaskInfo.State.error:
                            raise task.info.error
            version = update.version
    finally:
        if filter:
            filter.Destroy()
def getvmname():#打印所有虚拟机名
    content = si.RetrieveContent()
    for child in content.rootFolder.childEntity:
        if hasattr(child, 'vmFolder'):
            datacenter = child
            vmFolder = datacenter.vmFolder
            vmList = vmFolder.childEntity
            for vm in vmList:
                print(vm.summary.config.name)
                print(vm.name)
def getvmstatus(vm_name):#获取虚拟机状态
    content = si.RetrieveContent()
    for child in content.rootFolder.childEntity:
        if hasattr(child, 'vmFolder'):
            datacenter = child
            vmFolder = datacenter.vmFolder
            vmList = vmFolder.childEntity
            for vm in vmList:
                if vm.summary.config.name == vm_name :
                    print(vm.summary.runtime.powerState)

def poweronvm(vm_name):#打开虚拟机
    content = si.content
    objView = content.viewManager.CreateContainerView(content.rootFolder,[vim.VirtualMachine],True)
    vmList = objView.view
    objView.Destroy()
    tasks = [vm.PowerOn() for vm in vmList if vm.name in vm_name]
    print(tasks)
    WaitForTasks(tasks, si)
    print("虚拟机启动成功")

def get_vmsnapshotinfo(vm_name):#查看快照信息
    content = si.RetrieveContent()
    container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
    for c in container.view:
        if c.name == vm_name:
            snapshots = c.snapshot.rootSnapshotList
            return snapshots
def get_vmlist():#获取虚拟机列表
    content = si.RetrieveContent()
    for child in content.rootFolder.childEntity:
        if hasattr(child, 'vmFolder'):
            datacenter = child
            vmFolder = datacenter.vmFolder
            vmList = vmFolder.childEntity
            return vmList
def re_snapshot(vm_name,snapshot_name):##恢复快照
    for vm in get_vmlist():
        pass
        #print(vm.name)
        if vm.name == vm_name:
            snapshots = vm.snapshot.rootSnapshotList
            for snapshot in snapshots: 
                print(snapshot.name)               
                if snapshot_name == snapshot.name:
                    snap_obj = snapshot.snapshot
                    print ("恢复快照", snapshot.name)
                    task = [snap_obj.RevertToSnapshot_Task()]
                    WaitForTasks(task, si)

#re_snapshot("虚拟机名","快照名") #恢复快照 
#print(get_vmsnapshotinfo("虚拟机名")) #获取虚拟机快照信息
#print(get_vmsnapshotinfo("虚拟机名"))#查看虚拟机快照
#poweronvm("虚拟机名") #打开虚拟机

其它功能我闲了就增加
如果有其它着急需求或者使用方法可以回帖寻求帮助

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章