Home > database >  Error when execute Invoke-Command powershell session using subprocess python
Error when execute Invoke-Command powershell session using subprocess python

Time:12-21

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"

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 ... ------------ ------------ ----- ----------- ...\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\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. Correct the reported errors and try again.\r\n CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException\r\n FullyQualifiedErrorId : UnexpectedToken\r\n \r\n")

CodePudding user response:

The problem is caused by trying to pass a Powershell object as its string represntation.

When one calls New-PSSession, it will return a Powershell Session object. Your code doesn't do anything to the object, so Powershell will print it, a bit like one does with Python object __str()__. Now, in Powershell, these default output forms are often table-oriented. 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. 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. Which will contain all the minus chars and other junk. Powershell's parser doesn't understand any of that, it expects objects. 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. So when you call for a Powershell shell session the second time for Invoke-Command, the remoting session is not in scope over there. 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.

  • Related