Python 如何使用pyvmomi创建虚拟机

Python 如何使用pyvmomi创建虚拟机,python,pyvmomi,Python,Pyvmomi,我正在尝试创建一个python程序,该程序将创建提供数量相同的虚拟机。我已经使用社区示例脚本尽可能多地运行,但现在我完全被卡住了 #!/usr/bin/env python """ vSphere SDK for Python program for creating tiny VMs (1vCPU/128MB) """ import atexit import hashlib import json import random import time import requests

我正在尝试创建一个python程序,该程序将创建提供数量相同的虚拟机。我已经使用社区示例脚本尽可能多地运行,但现在我完全被卡住了

#!/usr/bin/env python


"""
vSphere SDK for Python program for creating tiny VMs (1vCPU/128MB)
"""

import atexit
import hashlib
import json

import random
import time

import requests
from pyVim import connect
from pyVmomi import vim

from tools import cli
from tools import tasks

from add_nic_to_vm import add_nic, get_obj



def get_args():
    """
    Use the tools.cli methods and then add a few more arguments.
    """
    parser = cli.build_arg_parser()

    parser.add_argument('-c', '--count',
                        type=int,
                        required=True,
                        action='store',
                        help='Number of VMs to create')

    parser.add_argument('-d', '--datastore',
                        required=True,
                        action='store',
                        help='Name of Datastore to create VM in')

    parser.add_argument('--datacenter',
                        required=True,
                        help='Name of the datacenter to create VM in.')

    parser.add_argument('--folder',
                        required=True,
                        help='Name of the vm folder to create VM in.')

    parser.add_argument('--resource-pool',
                        required=True,
                        help='Name of resource pool to create VM in.')

    parser.add_argument('--opaque-network',
                        help='Name of the opaque network to add to the new VM')

    # NOTE (hartsock): as a matter of good security practice, never ever
    # save a credential of any kind in the source code of a file. As a
    # matter of policy we want to show people good programming practice in
    # these samples so that we don't encourage security audit problems for
    # people in the future.

    args = parser.parse_args()

    return cli.prompt_for_password(args)



def create_dummy_vm(vm_name, service_instance, vm_folder, resource_pool,
                    datastore):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=vm_name, memoryMB=128, numCPUs=1,
                               files=vmx_file, guestId='dosGuest',
                               version='vmx-07')

    print("Creating VM {}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])

A=1
def main():
    """
    Simple command-line program for creating Dummy VM based on Marvel character
    names
    """
    name = "computer" + str(A)

    args = get_args()



    service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                     user=args.user,
                                                     pwd=args.password,
                                                     port=int(args.port))
    if not service_instance:
        print("Could not connect to the specified host using specified "
              "username and password")
        return -1

    atexit.register(connect.Disconnect, service_instance)

    content = service_instance.RetrieveContent()
    datacenter = get_obj(content, [vim.Datacenter], args.datacenter)
    vmfolder = get_obj(content, [vim.Folder], args.folder)
    resource_pool = get_obj(content, [vim.ResourcePool], args.resource_pool)



    vm_name =  name
    create_dummy_vm(vm_name, service_instance, vmfolder, resource_pool,
                        args.datastore)
    A + 1
    if args.opaque_network:
            vm = get_obj(content, [vim.VirtualMachine], vm_name)
            add_nic(service_instance, vm, args.opaque_network)
    return 0


# Start program
if __name__ == "__main__":
    main()
运行时出现的错误是

   Creating VM computer1...
Traceback (most recent call last):
  File "create_vm.py", line 142, in <module>
    main()
  File "create_vm.py", line 133, in main
    args.datastore)
  File "create_vm.py", line 98, in create_dummy_vm
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
AttributeError: 'NoneType' object has no attribute 'CreateVM_Task'
正在创建虚拟机计算机1。。。
回溯(最近一次呼叫最后一次):
文件“create_vm.py”,第142行,在
main()
文件“create_vm.py”,第133行,在main中
args.datastore)
文件“create_vm.py”,第98行,在create_dummy_vm中
task=vm\u folder.CreateVM\u task(config=config,pool=resource\u pool)
AttributeError:“非类型”对象没有属性“CreateVM\u任务”

我知道我的CreateVM_任务返回的参数为none,但我似乎不明白为什么

问题在于配置参数。使用当前代码,数据中心和vmfolder对象在打印时返回为无。为了解决这个问题,我将其编辑到下面的块中

content = service_instance.RetrieveContent()
datacenter = content.rootFolder.childEntity[0]
vmfolder = datacenter.vmFolder
hosts = datacenter.hostFolder.childEntity
resource_pool = hosts[0].resourcePool

无论您在这条语句中想说什么,都是错误的,在Python-3.x中是不可能的。您确定使用3.x吗?我在Python3.7环境中工作,我正在使用的sdk示例代码也在3.x中。那条线是我用它制作的样本的一部分。我把它拿走了,因为我认为它不需要。删除该行后,错误仍然存在。