简体   繁体   English

使用子进程 python 执行 Invoke-Command powershell 会话时出错

[英]Error when execute Invoke-Command powershell session using subprocess python

i encounter error when execute my code.我在执行我的代码时遇到错误。 The main purpose of the code is to create new-Pssession in powershell by using subprocess python then utilize the session to execute "Get-process"该代码的主要目的是使用子进程 python 在 powershell 中创建新的 Pssession,然后利用该会话执行“Get-process”

Here sample of my code:这是我的代码示例:

import subprocess

result=subprocess.run(['powershell.exe',' New-PSSession -ComputerName 12.455.66.7777 -Credential (New-Object System.Management.Automation.PSCredential("username",(ConvertTo-SecureString "password" -AsPlainText -Force)))'],capture_output=True)
session=result.stdout.decode().strip()
print(session)
result=subprocess.run(["powershell.exe","-Command", f"Invoke-Command -Session {session} -ScriptBlock {{Get-Process}}"], capture_output=True)
print(result)

and i have this error:我有这个错误:

Blockquote CompletedProcess(args=['powershell.exe', '-Command', 'Invoke-Command -Session Id Name ComputerName ComputerType State ConfigurationName Availability\r\n -- ---- ------------ ------------ ----- ----------------- ------------\r\n 1 WinRM1 11.888.32.09 RemoteMachine Opened Microsoft.PowerShell Available -ScriptBlock {Get-Process}'], returncode=1, stdout=b'', stderr=b"At line:3 char:5\r\n+ 1 WinRM1 10.229.78.59 RemoteMachine Opened Mic...\r\n+ ~~~~~~\r\nUnexpected token 'WinRM1' in expression or statement.\r\nAt line:2 char:5\r\n+ -- ---- ------------ ------------ ----- ---...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:7\r\n+ -- ---- ------------ ------------ ----- ---...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:21\r\n+... ------------ ------------ ----- ---------- Blockquote CompletedProcess(args=['powershell.exe', '-Command', 'Invoke-Command -Session Id Name ComputerName ComputerType State ConfigurationName Availability\r\n -- ---- ------------ -- ---------- ----- -------------- --------------\r \n 1 WinRM1 11.888.32.09 RemoteMachine 打开 Microsoft.PowerShell 可用 -ScriptBlock {Get-Process}'], returncode=1, stdout=b'', stderr=b"At line:3 char:5\r\n+ 1 WinRM1 10.229.78.59 RemoteMachine Opened Mic...\r\n+ ~~~~~~\r\n表达式或语句中出现意外标记“WinRM1”。\r\nAt line:2 char:5\r\n+ -- -- -- ---------- -------------- ----- ---...\r\n+ ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~\r\n'--' 运算符仅适用于变量或属性。\r\nAt line:2 char:7\r\n+ -- ---- -------- ----- ------------ ----- ----...\r\n+ ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n' --' 运算符仅适用于变量或属性。\r\nAt line:2 char:21\r\n+... ------------ -------- --- ----- ------------ -...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:23\r\n+... ------------ ------------ ----- -------------...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:25\r\n+... ------------ ------------ ----- ---------------...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:27\r\n+... ------------ ------------ ----- -----------------...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:29\r\n+... ------------ ------------ ----- -----------------...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:31\r\n+... ------------ - -...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~\r\n“--”运算符仅适用于变量或属性。\r\nAt line:2 char:23\r\n+... - ---------- ---------- ----- ----------...\r\n+ ~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~\r\n'--' 运算符仅适用于变量或属性。\r\nAt line:2 char:25\r\n+... ---------- - ---------- ----- --------------...\r\n+ ~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\ n'--' 运算符仅适用于变量或属性。\r\nAt line:2 char:27\r\n+... ---------- ------ ----- ----- ----------------...\r\n+ ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n“--”运算符仅适用于变量或属性。\r\nAt line:2 char:29\r\n+... ---------- -------------- ---- ----------------...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n“--”运算符仅适用于变量或属性。\r\nAt line:2 char:31\r\n+... ------------ - ----------- ----- -----------------...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nAt line:2 char:37\r\n+... -------- ------------ ----- ----------------- -----...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\nThe '--' operator works only on variables or on properties.\r\nNot all parse errors were reported. ---------- ----- ----------------...\r\n+ ~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\ n'--' 运算符仅适用于变量或属性。\r\nAt line:2 char:37\r\n+... ------ ---------- - ----- ---------------- -----...\r\n+ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n'--'运算符仅适用于变量或属性。\r\n并未报告所有分析错误。 Correct the reported errors and try again.\r\n + CategoryInfo: ParserError: (:) [], ParentContainsErrorRecordException\r\n + FullyQualifiedErrorId: UnexpectedToken\r\n \r\n")更正报告的错误并重试。\r\n + CategoryInfo: ParserError: (:) [], ParentContainsErrorRecordException\r\n + FullyQualifiedErrorId: UnexpectedToken\r\n \r\n")

The problem is caused by trying to pass a Powershell object as its string represntation.问题是由于试图将 Powershell 对象作为其字符串表示传递而引起的。

When one calls New-PSSession , it will return a Powershell Session object.当调用New-PSSession时,它将返回一个 Powershell Session 对象。 Your code doesn't do anything to the object, so Powershell will print it, a bit like one does with Python object __str()__ .您的代码不会对该对象执行任何操作,因此 Powershell 将打印它,有点像对 Python 对象__str()__所做的那样。 Now, in Powershell, these default output forms are often table-oriented.现在,在 Powershell 中,这些默认输出形式通常是面向表格的。 That is, there are columns with headers and a divider of dashes/minus - characters.也就是说,有些列带有标题和破折号/减号分隔符-字符。 Like so,像这样,

PS C:\>New-PSSession -ComputerName testserver

 Id Name            ComputerName    ComputerType    State         ConfigurationName     Availability
 -- ----            ------------    ------------    -----         -----------------     ------------
  2 WinRM2          testserver     RemoteMachine   Opened        Microsoft.PowerShell     Available

The Python code reads all that - ID, Name, Computername... --, ----,... - and so on as a string. Python 代码读取所有这些 - ID, Name, Computername... --, ----,...等等作为字符串。 On your next subprocess command, the whole broken mess of a string instead of an actual object is passed as a parameter value to -Session .在您的下一个 subprocess 命令中,字符串而不是实际对象的整个混乱作为参数值传递给-Session Which will contain all the minus chars and other junk.其中将包含所有减号字符和其他垃圾。 Powershell's parser doesn't understand any of that, it expects objects. Powershell 的解析器不理解这些,它需要对象。 The bunch of minus characters are interpreted as substraction operators and, well, nothing works.一堆减号字符被解释为减法运算符,嗯,没有任何作用。

But wait, it gets worse.但是等等,情况变得更糟了。 Powershell's sessions are not global. Powershell 的会话不是全局的。 So when you call for a Powershell shell session the second time for Invoke-Command , the remoting session is not in scope over there.因此,当您第二次为Invoke-Command Powershell shell 会话时,远程会话不在那边的范围内 So even if you manage to get the session out unmangled (there's, say, Export-CliXML serialization for that), it wouldn't work in the second shell session anyway.因此,即使您设法使会话不受干扰(例如,为此进行了Export-CliXML序列化),它也不会在第二个 shell 会话中工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM