pywinrm is a Python client for Windows Remote Management (WinRM). This allows you to invoke commands on target Windows machines from any machine that can run Python.
WinRM allows you to call native objects in Windows. This includes, but is not limited to, running batch scripts, powershell scripts and fetching WMI variables. For more information on WinRM, please visit Microsoft's WinRM site.
- Linux, Mac OS X or Windows
- CPython 2.6, 2.7, 3.2, 3.3 or PyPy 1.9
- python-kerberos is optional
$ pip install http://github.com/diyan/pywinrm/archive/master.zip
$ sudo apt-get install python-dev libkrb5-dev
$ pip install kerberos
import winrm
s = winrm.Session('http://windows-host.example.com:5985/wsman', auth=('john.smith', 'secret'))
r = s.run_cmd('ipconfig', ['/all'])
>>> r.status_code
0
>>> r.std_out
Windows IP Configuration
Host Name . . . . . . . . . . . . : WINDOWS-HOST
Primary Dns Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Hybrid
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
...
>>> r.std_err
Powershell scripts can be executed using WinRM. The script will be base64 UTF16 little endian encoded prior to sending to the Windows machines. Error messages are converted from the Powershell CLIXML format to a human readable format as a convenience.
import winrm
ps_script = """$strComputer = $Host
Clear
$RAM = WmiObject Win32_ComputerSystem
$MB = 1048576
"Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """
s = winrm.Session('http://windows-host.example.com:5985/wsman', auth=('john.smith', 'secret'))
r = s.run_ps(ps_script)
>>> r.status_code
0
>>> r.std_out
Installed Memory: 3840 MB
>>> r.std_err
from winrm.protocol import Protocol
p = Protocol(
endpoint='http://windows-host:5985/wsman',
transport='plaintext',
username='john.smith',
password='secret')
shell_id = p.open_shell()
command_id = p.run_command(shell_id, 'ipconfig', ['/all'])
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
winrm set winrm/config/client/auth @{Basic="true"}
winrm set winrm/config/service/auth @{Basic="true"}
winrm set winrm/config/service @{AllowUnencrypted="true"}
Want to help - send a pull request. I will accept good pull requests for sure.