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