pythonpython-3.xpowershellquotesdouble-quotes

How to put quotes in powershell with variables inside python?


I'm trying to use paramiko to send to the server via ssh. I can't get paramiko to send multiple ops in a row, so I made a powershell oneliner that works in ps:

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"

But I can't insert it as a string in python because quotes must be used everywhere in both python and powershell. Plus, I need to pass two variables to the powershell. I tried like this:

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)\"'

To check, I also print the command The result is this:

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)"

If I understand correctly - the variable is not replaced ( How to correctly place quotes so that everything works?


Solution

  • In this code, I've used f-strings (formatted strings) to insert the variables internal_number and gen_password into the PowerShell command. To escape the double quotes inside the PowerShell command, you need to use \". This way, the resulting commands string should contain the properly formatted PowerShell command that you can use in your paramiko SSH call.

    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)