运维离不开自动化,python的发展更是给自动化注入了一剂兴奋剂;还记得当时公司年会,大家都在嗨皮,苦逼的运维攻城狮还在卖力的给一个大客户手动开通500台云主机的情形,现在想想好傻O(∩_∩)O哈哈~。如果早点接触pyVmomi,就不至于这么苦逼了。 pyVmomi is the Python SDK for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter.官方如是说。自己这里写篇博客整理一下,也希望对还停留在手工时代的同学有所帮助。坏境配置:1、网络环境: 安装pyvmomi的server和VMware vCenter 网络打通;2、系统环境: pyvmomi用pip安装,所以需要有python和pip;pyvmomi 6.0.0需要的python版本支持为2.7, 3.3 和 3.4, 支持的vSphere 版本为:6.0, 5.5, 5.1 和 5.0。安装如下:
#!/usr/bin/env pythonVMware vSphere Python SDKCopyright (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, softwaredistributed 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 andlimitations 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')
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,