python结合pyvmomi批量关闭vmware虚拟机

#!/usr/bin/env python
#参考https://github.com/vmware/pyvmomi/blob/master/sample/poweronvm.py

"""
Python program for powering on vms on a host on which hostd is running
"""

from __future__ import print_function

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl

import argparse
import atexit
import getpass
import sys
import ssl

def GetArgs():
   """
   Supports the command-line arguments listed below.
   """

   parser = argparse.ArgumentParser(description='Process args for powering on a Virtual Machine')
   parser.add_argument('-s', '--host', required=True, action='store', help='Remote host to connect to')
   parser.add_argument('-o', '--port', type=int, default=443, action='store', help='Port to connect on')
   parser.add_argument('-u', '--user', required=True, action='store', help='User name to use when connecting to host')
   parser.add_argument('-p', '--password', required=False, action='store', help='Password to use when connecting to host')
   parser.add_argument('-v', '--vmname', required=True, action='append', help='Names of the Virtual Machines to power on')
   args = parser.parse_args()
   return args

def WaitForTasks(tasks, si):
   """
   Given the service instance si and tasks, it returns after all the
   tasks are complete
   """

   pc = si.content.propertyCollector

   taskList = [str(task) for task in tasks]

   # Create filter
   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

      # Loop looking for updates till the state moves to a completed state.
      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:
                     # Remove task from taskList
                     taskList.remove(str(task))
                  elif state == vim.TaskInfo.State.error:
                     raise task.info.error
         # Move to next version
         version = update.version
   finally:
      if filter:
         filter.Destroy()

# Start program
def main():
   """
   Simple command-line program for powering on virtual machines on a system.
   """

   # args = GetArgs()
   # if args.password:
   #    password = args.password
   # else:
   #    password = getpass.getpass(prompt='Enter password for host %s and user %s: ' % (args.host,args.user))

   try:
      # vmnames = args.vmname
      # 将需要开机的vmwarem_name用逗号或者空格拼凑起来
      vmnames = 'Mail_Server01,sss'
      if not len(vmnames):
         print("No virtual machine specified for poweron")
         sys.exit()

      context = None
      # 修改vcenter的IP、账号、密码等信息
      # 192.168.254.69 -o 443 -u zabbixmonitor -p zabbixmonitor -v Mail_Server01
      if hasattr(ssl, '_create_unverified_context'):
         context = ssl._create_unverified_context()
      si = SmartConnect(host='192.168.254.69',
                        user='zabbixmonitor',
                        pwd='zabbixmonitor',
                        port=443,
                        sslContext=context)
      if not si:
         print("Cannot connect to specified host using specified username and password")
         sys.exit()

      atexit.register(Disconnect, si)

      # Retreive the list of Virtual Machines from the inventory objects
      # under the rootFolder
      content = si.content
      objView = content.viewManager.CreateContainerView(content.rootFolder,
                                                        [vim.VirtualMachine],
                                                        True)
      vmList = objView.view
      # print(vmList)
      objView.Destroy()

      # Find the vm and power it on
      # 便利vmList拼凑任务
      for vm in vmList:
         print(vm.name)
      tasks = [vm.PowerOn() for vm in vmList if vm.name in vmnames]
      print(tasks)

      # Wait for power on to complete
      # 启动任务
      # WaitForTasks(tasks, si)

      print("Virtual Machine(s) have been powered on successfully")
   except vmodl.MethodFault as e:
      print("Caught vmodl fault : " + e.msg)
   except Exception as e:
      print("Caught Exception : " + str(e))

# Start program
if __name__ == "__main__":
   main()

# -s vcenter 的ip地址
# -u vcenter账号  -p vcenter密码
# -v 需要关机的虚拟机hostname
# [root@wondershareID_web03:/data/python]# python3 python_poweron.py -s IP -o 443 -u USERNAME -p PASSWORD -v VM_HOSTNAME

 

posted @ 2018-09-27 22:11  reblue520  阅读(879)  评论(0编辑  收藏  举报