Home > database >  How to use Python to represent the Powershell "ToBase64String" function
How to use Python to represent the Powershell "ToBase64String" function

Time:03-29

Because I want to call windows shell to run a command and to get the output from Python, I tried to encode the command string in Python, then run it by using

> powershell -EncodedCommand <base64 string from Python encode>

It will through an error because of the syntax.
The codes in Python looks like

s = '''Get-ADUser -Filter ('Surname -eq "aa" -and GivenName -eq "bb" -and Department -eq "cc"') | Select-Object -Property UserPrincipalName'''
bs = bytearray(s, 'utf-16')
base64.b64encode(bs)

But, when I use the Powershell function to encrypt my command string to a base64 string

PS > $bytes = [System.Text.Encoding]::Unicode.GetBytes("Get-ADUser -Filter ('Surname -eq `"aa`" -and GivenName -eq `"bb`" -and Department -eq `"cc`"') | Select-Object -Property UserPrincipalName")
PS > [Convert]::ToBase64String($bytes)

Afterward, I can get a valid base64 string to execute this command on normal windows shell successfully.

> powershell -EncodedCommand <base64 string encoded by Powershell in last two steps>

My question is what's the problem here? Or do I have another option to address the problem? Like, use the PowerShell parameter of "-Command" to run directly? Actually, I tried it with

> powershell -Command "Get-ADUser -Filter ('Surname -eq `"aa`" -and GivenName -eq `"bb`" -and Department -eq `"cc`"') | Select-Object -Property UserPrincipalName"

But it throughs an error of

Get-ADUser : Error parsing query: 'Surname -eq `aa` -and GivenName -eq `bb` -and Department -eq `cc`' Error Message: 's
yntax error' at position: '13'.
At line:1 char:1
  Get-ADUser -Filter ('Surname -eq `aa` -and GivenName -eq `bb` -and De ...
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : ParserError: (:) [Get-ADUser], ADFilterParsingException
      FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Micr
   osoft.ActiveDirectory.Management.Commands.GetADUser

CodePudding user response:

Note that bs = bytearray(s, 'utf-16') adds Byte order mark:

bs[0:2]
# bytearray(b'\xff\xfe')

To get the same result as PowerShell, use

bs = bytearray(s, 'utf-16-le')

Then:

bs[0:20]
# bytearray(b'G\x00e\x00t\x00-\x00A\x00D\x00U\x00s\x00e\x00r\x00')

which is the same as PowerShell:

$bytes[0..19] -join ' '
# 71 0 101 0 116 0 45 0 65 0 68 0 85 0 115 0 101 0 114 0
  • Related