Skip to content

Instantly share code, notes, and snippets.

@diyan
Created June 1, 2012 09:54
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save diyan/2850866 to your computer and use it in GitHub Desktop.
Save diyan/2850866 to your computer and use it in GitHub Desktop.
Python with PowerShell Remoting (Windows equivalent for Unix ssh sessions)
# Note that target_env.login and target_env.password is global variables
# Maybe I should add this into Fabric project (http://docs.fabfile.org/en/1.4.2/index.html).
# This is complicated task for sure but it would be nice if Fabric could use ssh under Linux and PowerShell Remoting under Windows.
def remote_sh(target_host, command_text, ignore_error=False):
print('run PowerShell script block at {0}: {1}'.format(target_host, command_text))
command_text = command_text.replace('"', '\'')
# -NoProfile -NonInteractive PowerShell parameters decrease execution time
power_shell_text = """\
powershell -NoProfile -NonInteractive
\"$secure_password = ConvertTo-SecureString '{1}' -asPlainText -Force;
$credentials = New-Object Management.Automation.PSCredential('{0}', $secure_password);
$remote_session = New-PSSession -ComputerName {2} -Credential $credentials;
Invoke-Command -Session $remote_session -ScriptBlock {{ {3} }};
$remote_last_exit_code = Invoke-Command -Session $remote_session -ScriptBlock {{ $LastExitCode }};
Remove-PSSession -Session $remote_session;
exit $remote_last_exit_code\"""".format(
target_env.login,
target_env.password,
target_host,
command_text)
power_shell_text = dedent(power_shell_text).replace('\n', ' ')
# This print call could be uncommented for debugging purposes
# print('run shell command: {0}'.format(power_shell_text))
error_code = os.system(power_shell_text)
if error_code and not ignore_error:
raise Exception('Failed to execute PowerShell script block on host {0}. Actual return code was {1} '
'but only zero value is expected. '
'Script block is "{2}".'.format(target_host, error_code, command_text))
return error_code
@anandnevase
Copy link

When I am executing same sample code on my machine, script remain in blocking state (i.e. powershell process in back ground never get closed).
Platform i am using is
OS : Windows 7 - 64bit
Python Version : Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32

@robertcatgithub
Copy link

This is pretty sweet ! small bite, tastes great !

Does exactly what I need: run remote PS1 script & commands.
I modified os.system() to proc = subprocess.Popen(power_shell_text, stdout=subprocess.PIPE, shell=True)
so I can process the big chunk of return info.

Alexey, did you ever release that library ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment