因为我想调用windows shell来运行命令并从Python获取输出,所以我尝试在Python中对命令字符串进行编码,然后使用
> powershell -EncodedCommand <base64 string from Python encode>
由于语法原因,它将通过一个错误。
Python中的代码看起来像
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)
但是,当我使用Powershell函数将命令字符串加密为base64字符串时
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)
之后,我可以获得一个有效的base64字符串来在普通的windows上成功地执行这个命令。
> powershell -EncodedCommand <base64 string encoded by Powershell in last two steps>
我的问题是这里有什么问题?还是我还有别的选择来解决这个问题?比如,使用PowerShell参数"-Command“直接运行?实际上,我试过了
> powershell -Command "Get-ADUser -Filter ('Surname -eq `"aa`" -and GivenName -eq `"bb`" -and Department -eq `"cc`"') | Select-Object -Property UserPrincipalName"
但它通过了一个错误
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
发布于 2022-03-28 10:15:42
注意,bs = bytearray(s, 'utf-16')
添加了字节顺序标记
bs[0:2]
# bytearray(b'\xff\xfe')
要获得与PowerShell相同的结果,请使用
bs = bytearray(s, 'utf-16-le')
然后:
bs[0:20]
# bytearray(b'G\x00e\x00t\x00-\x00A\x00D\x00U\x00s\x00e\x00r\x00')
与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
https://stackoverflow.com/questions/71642299
复制相似问题