如何在powershell中使用python中的变量添加引号?

问题描述 投票:0回答:1

我正在尝试使用 paramiko 通过 ssh 发送到服务器。 我无法让 paramiko 连续发送多个操作,所以我制作了一个在 ps 中工作的 powershell oneliner:

powershell.exe -noprofile -command "&Get-ADUser -Filter ('OfficePhone -like 888888') -Properties SID | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText Password! -Force -Verbose) -PAssThru | Unlock-ADAccount"

但我无法将其作为字符串插入到 python 中,因为在 python 和 powershell 中都必须使用引号。另外,我需要将两个变量传递给 powershell。 我尝试过这样的:

commands = 'powershell "&Get-ADUser -Filter (\"OfficePhone -like f"{internal_number}"\") -Properties SID | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText f"{gen_password}" -Force -Verbose) -PAssThru | Unlock-ADAccount)\"'

为了检查,我还打印了命令 结果是这样的:

powershell "&Get-ADUser -Filter ("OfficePhone -like f"{internal_number}"") -Properties SID | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText f"{gen_password}" -Force -Verbose) -PAssThru | Unlock-ADAccount)"

如果我理解正确 - 变量不会被替换( 如何正确放置引号以使一切正常?

python python-3.x powershell quotes double-quotes
1个回答
0
投票

在此代码中,我使用 f 字符串 (格式化字符串) 将变量 internal_numbergen_password 插入到 PowerShell 命令中。要转义 PowerShell 命令中的双引号,您需要使用 \"。这样,生成的命令字符串应包含格式正确的 PowerShell 命令,您可以在 paramiko SSH 调用中使用。

internal_number = "888888"
gen_password = "Password!"

commands = (
    f'powershell.exe -noprofile -command "&Get-ADUser -Filter (\\"OfficePhone -like {internal_number}\\") '
    f'-Properties SID | Set-ADAccountPassword -Reset -NewPassword (ConvertTo-SecureString '
    f'-AsPlainText \\"{gen_password}\\" -Force -Verbose) -PAssThru | Unlock-ADAccount"'
)
print(commands) 
© www.soinside.com 2019 - 2024. All rights reserved.