公司要自己开发私有云管理平台,我这边负责vmware部分的后台接口编写。

主要基于vmware官方的 python 接口 pyvmomi进行二次封装,

主要实现有虚拟机开关机注销;

虚拟机增删磁盘;

虚拟机快照增删还原;

虚拟机 html5的console界面

虚拟机网络管理

zabbix 监控 esxi的磁盘使用率 

zabbix 接受转发esxi的报警信息

本文展示快照功能,快照其实是一个很小的功能,主要是让大家了解下vmware快照的接口,网上没有干过我这个事情,中间有个遍历的算法

先上图

1实际效果

esxi如何设置定时快照 esxi虚拟机定时快照_vim

2、实际的数据


esxi如何设置定时快照 esxi虚拟机定时快照_vim_02

代码如下

from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
import atexit
import argparse
import getpass
import ssl
import random
import cgi, cgitb
import sys
import json


def wait_for_task(task):
    """ wait for a vCenter task to finish """
    task_done = False
    while not task_done:
        if task.info.state == 'success':
            return task.info.result

        if task.info.state == 'error':
            print ("there was an error")
            task_done = True
form = cgi.FieldStorage()
vmnames= form.getvalue('IP')
  
si = None
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
si = SmartConnect(host="10.20.11.3",
                     user="root",
                     pwd="vmware",
                     port=443,
                     sslContext=context)
atexit.register(Disconnect, si)
content = si.RetrieveContent()

container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
for c in container.view:
  if c.name == vmnames:
     obj = c
     break

try:
  obj.name
except Exception as e:
  res={'status':'failed','result':'IP is not found'}
  body = json.dumps(res)
  print ("Status: 200 OK")
  print ("Content-Type: application/json")
  print ("Content-Length: %d" % (len(body)))
  print ("")
  print (res)
  sys.exit()

output=[]
#遍历快照的树状结构 注意要设置为全局变量
def showlist(snapshot):

  global output

  output.append({snapshot.snapshot:[snapshot.name,snapshot.createTime.timestamp()]})

  for i in snapshot.childSnapshotList:
          showlist(i)



http://blog.51cto.com/superbigsea/1794633