Pyvmomi for VMware Automation

Source: Internet
Author: User

Pyvmomi for VMware Automation

O & M is inseparable from automation. The development of python has injected a dose of doping into automation. I still remember that at the company's annual meeting, everyone was doing well, the tough O & M team is still trying to manually activate 500 cloud hosts for a major account. Now, let's think about the silly O (Taobao _ Taobao) O Haha ~. If you get started with pyVmomi earlier, it won't be so hard.

PyVmomi is the Python SDK for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter. I want to write a blog here to help students who are still in the manual age.

Bad Environment Configuration:

1. Network Environment:

The server installed with pyvmomi is interconnected with the VMware vCenter network;

2. system environment:

Pyvmomi is installed with pip. Therefore, python and pip are required. python versions 2.7, 3.3, and 3.4 are required for pyvmomi 6.0.0, and vSphere versions 6.0, 5.5, 5.1, and 5.0 are supported.

The installation is as follows:

$ Sudoapt-getinstallpython-pip $ installation $ sudopipfreeze | greppyvmomi # Check the installed version of pyvmomi. version 6.0 is pyvmomi = 6.0.0 # If installed, upgrade pipinstall -- upgradepyvmomi

You can also download and install the source code package, https://github.com/vmware/pyvmomi.git:

$sudopythonsetup.pyinstall

3. pyvmomi provides some community sample projects. You can refer to writing your own code:

gitclonehttps://github.com/vmware/pyvmomi-community-samples.git

4. The following is the script for getting all VMS provided by pyvmomi:

#!/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_functionfrompyVim.connectimportSmartConnect,DisconnectimportargparseimportatexitimportgetpassimportssldefGetArgs():"""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()returnargsdefPrintVmInfo(vm,depth=1):"""Printinformationforaparticularvirtualmachineorrecurseintoafolderwithdepthprotection"""maxdepth=10#ifthisisagroupitwillhavechildren.ifitdoes,recurseintothem#andthenreturnifhasattr(vm,'childEntity'):ifdepth>maxdepth:returnvmList=vm.childEntityforcinvmList:PrintVmInfo(c,depth+1)returnsummary=vm.summaryprint("Name:",summary.config.name)print("Path:",summary.config.vmPathName)print("Guest:",summary.config.guestFullName)annotation=summary.config.annotationifannotation!=Noneandannotation!="":print("Annotation:",annotation)print("State:",summary.runtime.powerState)ifsummary.guest!=None:ip=summary.guest.ipAddressifip!=Noneandip!="":print("IP:",ip)ifsummary.runtime.question!=None:print("Question:",summary.runtime.question.text)print("")defmain():"""Simplecommand-lineprogramforlistingthevirtualmachinesonasystem."""args=GetArgs()ifargs.password:password=args.passwordelse:password=getpass.getpass(prompt='Enterpasswordforhost%sand''user%s:'%(args.host,args.user))context=ssl.SSLContext(ssl.PROTOCOL_TLSv1)context.verify_mode=ssl.CERT_NONEsi=SmartConnect(host=args.host,user=args.user,pwd=password,port=int(args.port),sslContext=context)ifnotsi:print("Couldnotconnecttothespecifiedhostusingspecified""usernameandpassword")return-1atexit.register(Disconnect,si)content=si.RetrieveContent()forchildincontent.rootFolder.childEntity:ifhasattr(child,'vmFolder'):datacenter=childvmFolder=datacenter.vmFoldervmList=vmFolder.childEntityforvminvmList:PrintVmInfo(vm)return0#Startprogramif__name__=="__main__":main()

5. The output format after execution is as follows:

References:

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

Https://github.com/vmware/pyvmomi

Https://pypi.python.org/pypi/pyvmomi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.