【发布时间】:2017-04-16 23:08:41
【问题描述】:
是否有人知道是否有一种方法可以使用 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)
基于 stdout 的内容,我想连接回同一个 powershell 会话并使用 $Results 变量/对象更多一些。但是,当我执行另一个 s.run_ps() 时,我会得到一个全新的 powershell 会话,其中没有在前一个会话中创建的对象或变量。
有没有人知道如何连接回持久的 powershell 会话?我想知道这是否可能......
我不能在新的 powershell 会话中重新创建所有内容的原因是:
1) 我正在调用的 COM 对象方法需要几分钟才能运行,如果我需要解析多次,这可能很容易叠加到 30 分钟或更长时间。
2) COM 对象以数组的形式返回结果,并且并不总是以相同的顺序返回它们。所以,当我重新运行 COM 对象方法并去操作它们时,我不能指望数组项再次在同一个地方。
如果我能以某种方式从 powershell 会话中获取标准输出,执行需要在 Python 脚本中完成的解析(和其他库调用),然后回调到同一个 PowerShell 会话,其中所有的变量和对象在第一次调用时被保留。
【问题讨论】:
标签: python powershell winrm