pyvmomi 实现VMware自动化
pyvmomi 实现VMware自动化
运维离不开自动化,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。
安装如下:
$sudoapt-getinstallpython-pip $sudopipinstallpyvmomi $sudopipfreeze|greppyvmomi#查看安装的pyvmomi版本,现在是6.0版本 pyvmomi==6.0.0#如果已经安装过,升级用pipinstall--upgradepyvmomi
或者也可以下载源码包安装,https://github.com/vmware/pyvmomi.git:
$sudopythonsetup.pyinstall
3、pyvmomi提供了一些社区样本项目,可以参考编写自己的代码:
gitclonehttps://github.com/vmware/pyvmomi-community-samples.git
4、下面是 pyvmomi给出的获取所有vm的脚本:
#!/usr/bin/envpython #VMwarevSpherePythonSDK #Copyright(c)2008-2015VMware,Inc.AllRightsReserved. # #LicensedundertheApacheLicense,Version2.0(the"License"); #youmaynotusethisfileexceptincompliancewiththeLicense. #YoumayobtainacopyoftheLicenseat # #http://www.apache.org/licenses/LICENSE-2.0 # #Unlessrequiredbyapplicablelaworagreedtoinwriting,software #distributedundertheLicenseisdistributedonan"ASIS"BASIS, #WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. #SeetheLicenseforthespecificlanguagegoverningpermissionsand #limitationsundertheLicense. """ PythonprogramforlistingthevmsonanESX/vCenterhost """ from__future__importprint_function frompyVim.connectimportSmartConnect,Disconnect importargparse importatexit importgetpass importssl defGetArgs(): """ Supportsthecommand-lineargumentslistedbelow. """ parser=argparse.ArgumentParser( description='ProcessargsforretrievingalltheVirtualMachines') parser.add_argument('-s','--host',required=True,action='store', help='Remotehosttoconnectto') parser.add_argument('-o','--port',type=int,default=443,action='store', help='Porttoconnecton') parser.add_argument('-u','--user',required=True,action='store', help='Usernametousewhenconnectingtohost') parser.add_argument('-p','--password',required=False,action='store', help='Passwordtousewhenconnectingtohost') args=parser.parse_args() returnargs defPrintVmInfo(vm,depth=1): """ Printinformationforaparticularvirtualmachineorrecurseintoafolder withdepthprotection """ maxdepth=10 #ifthisisagroupitwillhavechildren.ifitdoes,recurseintothem #andthenreturn ifhasattr(vm,'childEntity'): ifdepth>maxdepth: return vmList=vm.childEntity forcinvmList: 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 ifannotation!=Noneandannotation!="": print("Annotation:",annotation) print("State:",summary.runtime.powerState) ifsummary.guest!=None: ip=summary.guest.ipAddress ifip!=Noneandip!="": print("IP:",ip) ifsummary.runtime.question!=None: print("Question:",summary.runtime.question.text) print("") defmain(): """ Simplecommand-lineprogramforlistingthevirtualmachinesonasystem. """ args=GetArgs() ifargs.password: password=args.password else: password=getpass.getpass(prompt='Enterpasswordforhost%sand' '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) ifnotsi: print("Couldnotconnecttothespecifiedhostusingspecified" "usernameandpassword") return-1 atexit.register(Disconnect,si) content=si.RetrieveContent() forchildincontent.rootFolder.childEntity: ifhasattr(child,'vmFolder'): datacenter=child vmFolder=datacenter.vmFolder vmList=vmFolder.childEntity forvminvmList: PrintVmInfo(vm) return0 #Startprogram if__name__=="__main__": main()
5、执行之后输出格式如下:
参考资料:
http://vmware.github.io/pyvmomi-community-samples/#getting-started
https://github.com/vmware/pyvmomi
https://pypi.python.org/pypi/pyvmomi
评论暂时关闭