Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading