##// END OF EJS Templates
automation: capture additional exception when formatting...
Gregory Szorc -
r43487:6a350194 default
parent child Browse files
Show More
@@ -1,87 +1,87 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 Client
15 15 from pypsrp.powershell import (
16 16 PowerShell,
17 17 PSInvocationState,
18 18 RunspacePool,
19 19 )
20 20 import requests.exceptions
21 21
22 22
23 23 logger = logging.getLogger(__name__)
24 24
25 25
26 26 def wait_for_winrm(host, username, password, timeout=180, ssl=False):
27 27 """Wait for the Windows Remoting (WinRM) service to become available.
28 28
29 29 Returns a ``psrpclient.Client`` instance.
30 30 """
31 31
32 32 end_time = time.time() + timeout
33 33
34 34 while True:
35 35 try:
36 36 client = Client(
37 37 host,
38 38 username=username,
39 39 password=password,
40 40 ssl=ssl,
41 41 connection_timeout=5,
42 42 )
43 43 client.execute_ps("Write-Host 'Hello, World!'")
44 44 return client
45 45 except requests.exceptions.ConnectionError:
46 46 if time.time() >= end_time:
47 47 raise
48 48
49 49 time.sleep(1)
50 50
51 51
52 52 def format_object(o):
53 53 if isinstance(o, str):
54 54 return o
55 55
56 56 try:
57 57 o = str(o)
58 except TypeError:
58 except (AttributeError, TypeError):
59 59 o = pprint.pformat(o.extended_properties)
60 60
61 61 return o
62 62
63 63
64 64 def run_powershell(client, script):
65 65 with RunspacePool(client.wsman) as pool:
66 66 ps = PowerShell(pool)
67 67 ps.add_script(script)
68 68
69 69 ps.begin_invoke()
70 70
71 71 while ps.state == PSInvocationState.RUNNING:
72 72 ps.poll_invoke()
73 73 for o in ps.output:
74 74 print(format_object(o))
75 75
76 76 ps.output[:] = []
77 77
78 78 ps.end_invoke()
79 79
80 80 for o in ps.output:
81 81 print(format_object(o))
82 82
83 83 if ps.state == PSInvocationState.FAILED:
84 84 raise Exception(
85 85 'PowerShell execution failed: %s'
86 86 % ' '.join(map(format_object, ps.streams.error))
87 87 )
General Comments 0
You need to be logged in to leave comments. Login now