gpt4 book ai didi

python - PyWinrm 持久 PowerShell session

转载 作者:行者123 更新时间:2023-12-03 14:44:49 29 4
gpt4 key购买 nike

有谁知道是否有办法使用 PyWinrm 打开一个持久的 PowerShell session ,该 session 保持状态并且可以多次调用?我正在尝试执行以下操作:

#!/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)

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

有谁知道如何连接回持久的 powershell session ?我想知道这是否可能......

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

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

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

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

最佳答案

您应该使用 pypsrp ,它 native 使用 PowerShell 远程处理。
GitHub 存储库中的示例将向您展示如何操作,您可以继续使用 .add_script()add_cmdlet()在 session 中调用多个电话。
WinRM(以及扩展名 pywinrm )与 PowerShell 并不严格相关,因此您正在进行的调用可能只是打开 powershell.exe无论您发送什么。
PSRP 是一个单独的协议(protocol),它通过 WinRM 作为其传输方式运行,因此您将连接到托管的 PowerShell session 。

关于python - PyWinrm 持久 PowerShell session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925434/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com