PyWinrm 持久 PowerShell 会话

Aus*_*ler 6 python powershell winrm

有没有人知道是否有一种方法可以使用 PyWinrm 打开持久的 PowerShell 会话,该会话可以维护状态并且可以多次调用?我正在尝试执行以下操作:

#!/bin/python

import winrm

# Initialize some COM object and call a method storing the results
# in $Results and then print $Results to stdout
ps_script = """
$SomeObject = New-Object -ComObject Some.Com.Object
$Results = SomeObject.DoThing
$Results
"""

# Create winrm connection
s = winrm.Session('https://server.domain.local', auth=('username', 'password'), transport='kerberos')

# Call the ps_script - contents of $Results is returned as a string
r = s.run_ps(ps_script)

# Parse the contents of $Results returned from the $Results variable
# in the ps script
parse_stdout_from_script(r.stdout)

# Based on results from parsing previous stdout, connect back to the
# same powershell session to manipulate the $Results variable some more
r = s.run_ps(new_ps_script_to_manipulate_existing_objects)
Run Code Online (Sandbox Code Playgroud)

根据 stdout 的内容,我想连接回同一个 powershell 会话并更多地使用 $Results 变量/对象。但是,当我执行另一个 s.run_ps() 时,我得到了一个全新的 powershell 会话,其中没有在上一个会话中创建的任何对象或变量。

有没有人知道如何连接回持久的 powershell 会话?我想知道这是否可能......

我不能在新的 powershell 会话中重新创建所有内容的原因是:

1) 我正在调用的 COM 对象方法需要几分钟才能运行,如果我需要多次解析,这很容易累积到 30 分钟或更长时间。

2) COM 对象以数组形式返回结果,并不总是以相同的顺序返回它们。因此,当我重新运行 COM 对象方法并去操作它们时,我不能指望数组项再次位于同一位置。

如果我能以某种方式从 powershell 会话中获取 stdout,执行需要在 Python 脚本中完成的解析(和其他库调用),然后回调到所有变量和对象的同一个 PowerShell 会话,那就太好了从第一次调用开始保留。

bri*_*ist 2

您应该使用pypsrp,它本身使用 PowerShell 远程处理。

GitHub 存储库中的示例将向您展示如何在会话中持续使用.add_script()add_cmdlet()进行多个调用。

WinRM(以及扩展名pywinrm)与 PowerShell 并不严格相关,因此您正在执行的调用可能只是powershell.exe随您发送的任何内容打开。

PSRP 是一个单独的协议,它通过 WinRM 作为其传输运行,因此您将连接到托管的 PowerShell 会话。