pyvmomi 實現VMware自動化

    運維離不開自動化,python的發展更是給自動化注入了一劑興奮劑;還記得當時公司年會,你們都在嗨皮,苦逼的運維攻城獅還在賣力的給一個大客戶手動開通500臺雲主機的情形,如今想一想好傻O(∩_∩)O哈哈~。若是早點接觸pyVmomi,就不至於這麼苦逼了。python

    pyVmomi is the Python SDK for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter.官方如是說。本身這裏寫篇博客整理一下,也但願對還停留在手工時代的同窗有所幫助。git

壞境配置:github

一、網絡環境:express

    安裝pyvmomi的server和VMware vCenter 網絡打通;apache

二、系統環境:bash

    pyvmomi用pip安裝,因此須要有python和pip;pyvmomi 6.0.0須要的python版本支持爲2.7, 3.3 和 3.4, 支持的vSphere 版本爲:6.0, 5.5, 5.1 和 5.0。網絡

安裝以下:app

$sudo apt-get install python-pip
$sudo pip install pyvmomi
$sudo pip freeze | grep pyvmomi     #查看安裝的pyvmomi版本,如今是6.0版本
pyvmomi==6.0.0        #若是已經安裝過,升級用pip install --upgrade pyvmomi

或者也能夠下載源碼包安裝,https://github.com/vmware/pyvmomi.git:less

$sudo python setup.py install

三、pyvmomi提供了一些社區樣本項目,能夠參考編寫本身的代碼:運維

git clone https://github.com/vmware/pyvmomi-community-samples.git

四、下面是 pyvmomi給出的獲取全部vm的腳本:

#!/usr/bin/env python
# VMware vSphere Python SDK
# Copyright (c) 2008-2015 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Python program for listing the vms on an ESX / vCenter host
"""

from __future__ import print_function

from pyVim.connect import SmartConnect, Disconnect

import argparse
import atexit
import getpass
import ssl

def GetArgs():
   """
   Supports the command-line arguments listed below.
   """
   parser = argparse.ArgumentParser(
       description='Process args for retrieving all the Virtual Machines')
   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')
   args = parser.parse_args()
   return args


def PrintVmInfo(vm, depth=1):
   """
   Print information for a particular virtual machine or recurse into a folder
    with depth protection
   """
   maxdepth = 10

   # if this is a group it will have children. if it does, recurse into them
   # and then return
   if hasattr(vm, 'childEntity'):
      if depth > maxdepth:
         return
      vmList = vm.childEntity
      for c in vmList:
         PrintVmInfo(c, depth+1)
      return

   summary = vm.summary
   print("Name       : ", summary.config.name)
   print("Path       : ", summary.config.vmPathName)
   print("Guest      : ", summary.config.guestFullName)
   annotation = summary.config.annotation
   if annotation != None and annotation != "":
      print("Annotation : ", annotation)
   print("State      : ", summary.runtime.powerState)
   if summary.guest != None:
      ip = summary.guest.ipAddress
      if ip != None and ip != "":
         print("IP         : ", ip)
   if summary.runtime.question != None:
      print("Question  : ", summary.runtime.question.text)
   print("")

def main():
   """
   Simple command-line program for listing the 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))


   context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
   context.verify_mode = ssl.CERT_NONE
   si = SmartConnect(host=args.host,
                     user=args.user,
                     pwd=password,
                     port=int(args.port),
                     sslContext=context)
   if not si:
       print("Could not connect to the specified host using specified "
             "username and password")
       return -1

   atexit.register(Disconnect, si)

   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:
            PrintVmInfo(vm)
   return 0

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

五、執行以後輸出格式以下:

wKiom1bEU9iRwz2kAACOQ5igs9Q865.png

參考資料:

http://vmware.github.io/pyvmomi-community-samples/#getting-started

https://github.com/vmware/pyvmomi

https://pypi.python.org/pypi/pyvmomi

相關文章
相關標籤/搜索