| 1 |
# winrm.py - Interact with Windows Remote Management (WinRM) |
| 2 |
# |
| 3 |
# Copyright 2019 Gregory Szorc <[email protected]> |
| 4 |
# |
| 5 |
# This software may be used and distributed according to the terms of the |
| 6 |
# GNU General Public License version 2 or any later version. |
| 7 |
|
| 8 |
# no-check-code because Python 3 native. |
| 9 |
|
| 10 |
import logging |
| 11 |
import pprint |
| 12 |
import time |
| 13 |
|
| 14 |
from pypsrp.client import Client |
| 15 |
from pypsrp.powershell import ( |
| 16 |
PowerShell, |
| 17 |
PSInvocationState, |
| 18 |
RunspacePool, |
| 19 |
) |
| 20 |
import requests.exceptions |
| 21 |
|
| 22 |
|
| 23 |
logger = logging.getLogger(__name__) |
| 24 |
|
| 25 |
|
| 26 |
def wait_for_winrm(host, username, password, timeout=180, ssl=False): |
| 27 |
"""Wait for the Windows Remoting (WinRM) service to become available. |
| 28 |
|
| 29 |
Returns a ``psrpclient.Client`` instance. |
| 30 |
""" |
| 31 |
|
| 32 |
end_time = time.time() + timeout |
| 33 |
|
| 34 |
while True: |
| 35 |
try: |
| 36 |
client = Client( |
| 37 |
host, |
| 38 |
username=username, |
| 39 |
password=password, |
| 40 |
ssl=ssl, |
| 41 |
connection_timeout=5, |
| 42 |
) |
| 43 |
client.execute_ps("Write-Host 'Hello, World!'") |
| 44 |
return client |
| 45 |
except requests.exceptions.ConnectionError: |
| 46 |
if time.time() >= end_time: |
| 47 |
raise |
| 48 |
|
| 49 |
time.sleep(1) |
| 50 |
|
| 51 |
|
| 52 |
def format_object(o): |
| 53 |
if isinstance(o, str): |
| 54 |
return o |
| 55 |
|
| 56 |
try: |
| 57 |
o = str(o) |
| 58 |
except (AttributeError, TypeError): |
| 59 |
o = pprint.pformat(o.extended_properties) |
| 60 |
|
| 61 |
return o |
| 62 |
|
| 63 |
|
| 64 |
def run_powershell(client, script): |
| 65 |
with RunspacePool(client.wsman) as pool: |
| 66 |
ps = PowerShell(pool) |
| 67 |
ps.add_script(script) |
| 68 |
|
| 69 |
ps.begin_invoke() |
| 70 |
|
| 71 |
while ps.state == PSInvocationState.RUNNING: |
| 72 |
ps.poll_invoke() |
| 73 |
for o in ps.output: |
| 74 |
print(format_object(o)) |
| 75 |
|
| 76 |
ps.output[:] = [] |
| 77 |
|
| 78 |
ps.end_invoke() |
| 79 |
|
| 80 |
for o in ps.output: |
| 81 |
print(format_object(o)) |
| 82 |
|
| 83 |
if ps.state == PSInvocationState.FAILED: |
| 84 |
raise Exception( |
| 85 |
'PowerShell execution failed: %s' |
| 86 |
% ' '.join(map(format_object, ps.streams.error)) |
| 87 |
) |