我正在研究将现有的powercli部署脚本移至python / pyvmomi以获得多线程(它部署了许多VM)。原始脚本大量使用Invoke-VMScript通过VMware Tools将Powershell片段推送给每个来宾。

pyvmomi中的等效功能是什么?具体来说-通过工具(不是来宾网络)将Powershell脚本发送给来宾,是否使用提供的凭据运行它,然后收集输出?

我可以看到processManager.StartProgramInGuest,但这似乎是一个笨拙的三步过程(上传文件,运行文件,下载重定向的结果)-是powercli在后台执行的操作吗?

最佳答案

因此,为了提供某种封闭效果,并且因为无论如何我都找不到完整的示例,因此这是我的第一个建议。它是已经使用SmartConnect连接到vcenter服务器并设置self.si的类的一部分。它实际上并没有做太多的错误检查。您可以选择是要等待并获得输出,还是在启动命令后返回。 remote_cmd最初来自pyvmomi-community-samples,因此当前这两种方法之间有些重复。

def invoke_vmscript(self, vm_username, vm_password, vm_name, script_content, wait_for_output=False):

    script_content_crlf = script_content.replace('\n', '\r\n')

    content = self.si.content
    creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)
    vm = self.get_vm(vm_name)
    logger.debug("Invoke-VMScript Started for %s", vm_name)
    logger.debug("CREATING TEMP OUTPUT DIR")
    file_manager = content.guestOperationsManager.fileManager

    temp_dir = file_manager.CreateTemporaryDirectoryInGuest(vm, creds, "nodebldr_",
                                                            "_scripts")
    try:
        file_manager.MakeDirectoryInGuest(vm, creds, temp_dir, False)
    except vim.fault.FileAlreadyExists:
        pass
    temp_script_file = file_manager.CreateTemporaryFileInGuest(vm, creds, "nodebldr_",
                                                               "_script.ps1",
                                                               temp_dir)
    temp_output_file = file_manager.CreateTemporaryFileInGuest(vm, creds, "nodebldr_",
                                                               "_output.txt",
                                                               temp_dir)
    logger.debug("SCRIPT FILE: " + temp_script_file)
    logger.debug("OUTPUT FILE: " + temp_output_file)
    file_attribute = vim.vm.guest.FileManager.FileAttributes()
    url = file_manager.InitiateFileTransferToGuest(vm, creds, temp_script_file,
                                                   file_attribute,
                                                   len(script_content_crlf), True)
    logger.debug("UPLOAD SCRIPT TO: " + url)
    r = requests.put(url, data=script_content_crlf, verify=False)
    if not r.status_code == 200:
        logger.debug("Error while uploading file")
    else:
        logger.debug("Successfully uploaded file")

    self.remote_cmd(vm_name, vm_username, vm_password, 'C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe',
                    "-Noninteractive {0} > {1}".format(temp_script_file, temp_output_file), temp_dir,
                    wait_for_end=wait_for_output)

    output = None
    if wait_for_output:
        dl_url = file_manager.InitiateFileTransferFromGuest(vm, creds,
                                                            temp_output_file)
        logger.debug("DOWNLOAD OUTPUT FROM: " + dl_url.url)
        r = requests.get(dl_url.url, verify=False)
        output = r.text
        logger.debug("Script Output was: %s", output)

    logger.debug("DELETING temp files & directory")
    file_manager.DeleteFileInGuest(vm, creds, temp_script_file)
    file_manager.DeleteFileInGuest(vm, creds, temp_output_file)
    file_manager.DeleteDirectoryInGuest(vm, creds, temp_dir, True)
    logger.debug("Invoke-VMScript COMPLETE")

    return output

def remote_cmd(self, vm_name, vm_username, vm_password, command, args, working_dir, wait_for_end=False, timeout=60):
    creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)
    vm = self.get_vm(vm_name)
    try:
        cmdspec = vim.vm.guest.ProcessManager.ProgramSpec(arguments=args, programPath=command)
        pid = self.si.content.guestOperationsManager.processManager.StartProgramInGuest(vm=vm, auth=creds,
                                                                                        spec=cmdspec)
        logger.debug("Started process %d on %s", pid, vm_name)
    except vmodl.MethodFault as error:
        print("Caught vmodl fault : ", error.msg)
        return -1

    n = timeout
    if wait_for_end:
        while n > 0:
            info = self.si.content.guestOperationsManager.processManager.ListProcessesInGuest(vm=vm, auth=creds,
                                                                                              pids=[pid])
            if info[0].endTime is not None:
                break
            logger.debug("Process not yet completed. Will wait %d seconds", n)
            sleep(1)
            n = n - 1
        logger.debug("Process completed with state: %s", info[0])

07-28 06:50