napalm-windows 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other transformations
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and incorporated
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combined Contribution(s) and the Work
78
+ to which such Contribution(s) was submitted. If You institute patent
79
+ litigation against any entity (including a cross-claim or counterclaim
80
+ in a lawsuit) alleging that the Work or any Contribution embodied
81
+ within the Work constitutes direct or contributory patent infringement,
82
+ then any patent licenses granted to You under this License for that
83
+ Work shall terminate as of the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the
86
+ Work or Derivative Works thereof in any medium, with or without
87
+ modifications, and in Source or Object form, provided that You
88
+ meet the following conditions:
89
+
90
+ (a) You must give any other recipients of the Work or Derivative
91
+ Works a copy of this License; and
92
+
93
+ (b) You must cause any modified files to carry prominent notices
94
+ stating that You changed the files; and
95
+
96
+ (c) You must retain, in the Source form of any Derivative Works
97
+ that You distribute, all copyright, patent, trademark, and
98
+ attribution notices from the Source form of the Work,
99
+ excluding those notices that do not pertain to any part of
100
+ the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, You must include a readable copy of the
104
+ attribution notices contained within such NOTICE file, in
105
+ at least one of the following places: within a NOTICE text file
106
+ distributed as part of the Derivative Works; within the Source
107
+ form or documentation, if provided along with the Derivative
108
+ Works; or, within a display generated by the Derivative Works,
109
+ if and wherever such third-party notices normally appear. The
110
+ contents of the NOTICE file are for informational purposes only
111
+ and do not modify the License. You may add Your own attribution
112
+ notices within Derivative Works that You distribute, alongside
113
+ or as an addendum to the NOTICE text from the Work, provided
114
+ that such additional attribution notices cannot be construed
115
+ as modifying the License.
116
+
117
+ You may add Your own license statement for Your modifications and
118
+ may provide additional grant of rights to use, copy, modify, merge,
119
+ publish, distribute, sublicense, and/or sell copies of the Work,
120
+ and to permit persons to whom the Work is furnished to do so,
121
+ subject to the following conditions:
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any conditions of TITLE,
141
+ MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE.
142
+ See the License for the specific language governing permissions and
143
+ limitations under the License.
144
+
145
+ 8. Limitation of Liability. In no event and under no legal theory,
146
+ whether in tort (including negligence), contract, or otherwise,
147
+ unless required by applicable law (such as deliberate and grossly
148
+ negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special,
150
+ incidental, or exemplary damages of any character arising as a
151
+ result of this License or out of the use or inability to use the
152
+ Work (even if such Contributor has been advised of the possibility
153
+ of such damages).
154
+
155
+ 9. Accepting Warranty or Additional Liability. While redistributing
156
+ the Work or Derivative Works thereof, You may choose to offer,
157
+ and charge a fee for, acceptance of support, warranty, indemnity,
158
+ or other liability obligations and/or rights consistent with this
159
+ License. However, in accepting such obligations, You may offer only
160
+ conditions consistent with this License, subject to the following
161
+ additional conditions:
162
+
163
+ (a) You may offer additional warranty, indemnity, or other liability
164
+ terms and conditions; and
165
+
166
+ (b) You may offer support for the Work in return for a fee.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ APPENDIX: How to apply the Apache License to your work.
171
+
172
+ To apply the Apache License to your work, attach the following
173
+ boilerplate notice, with the fields enclosed by brackets "[]"
174
+ replaced with your own identifying information. (Don't include
175
+ the brackets!) The text should be enclosed in the appropriate
176
+ comment syntax for the file format in question. It may also be
177
+ possible to make it available with a creative commons license.
178
+
179
+ Copyright 2026 Christian Manivong
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: napalm-windows
3
+ Version: 0.2.0
4
+ Summary: NAPALM driver for Windows hosts via PowerShell Remoting (WinRM)
5
+ Author-email: Christian Manivong <christian@manivong.de>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://git.netork.io/NAPALM/napalm-windows
8
+ Project-URL: Issues, https://git.netork.io/NAPALM/napalm-windows/issues
9
+ Project-URL: Changelog, https://git.netork.io/NAPALM/napalm-windows/src/branch/main/CHANGELOG.md
10
+ Keywords: napalm,network,automation,windows,winrm,powershell,psrp,driver
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: System :: Networking
21
+ Classifier: Topic :: System :: Systems Administration
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: napalm>=4.0
27
+ Requires-Dist: napalm-device-types>=4.21.1
28
+ Requires-Dist: pypsrp>=0.8
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Requires-Dist: pytest-cov>=5; extra == "dev"
32
+ Requires-Dist: mypy>=1.11; extra == "dev"
33
+ Requires-Dist: ruff>=0.6; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # napalm-windows
37
+
38
+ NAPALM driver for Windows Server 2016+ and Windows 10/11, part of the netOrk
39
+ driver family built on [`napalm-device-types`](https://git.netork.io/NAPALM/napalm-device-types).
40
+
41
+ Driver name: `windows` · Role: `OSDriver` · Transport: PowerShell Remoting
42
+ (PSRP) over WinRM via [`pypsrp`](https://pypi.org/project/pypsrp/).
43
+
44
+ ## Tested against
45
+
46
+ Not recorded yet: the fixtures under `tests/fixtures/synthetic/` are the JSON the scripts
47
+ are designed to emit, not output recorded from a host.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install napalm-windows
53
+ ```
54
+
55
+ ## How it works
56
+
57
+ Every getter sends one PowerShell script. The script projects the cmdlet
58
+ results onto flat, primitive fields and ends in `ConvertTo-Json`, so the
59
+ Python side parses JSON, never text. All device I/O goes through a single
60
+ seam (`PsrpTransport.run(script) -> str`), which is what the tests replace.
61
+
62
+ One runspace pool stays open per connection, so a poll pays the WinRM
63
+ handshake once.
64
+
65
+ ## Supported
66
+
67
+ | Method | Source |
68
+ |---|---|
69
+ | `get_facts` | `Win32_ComputerSystem`, `Win32_OperatingSystem`, `Win32_BIOS`, registry (`DisplayVersion`, `UBR`) |
70
+ | `get_interfaces` | `Get-NetAdapter` |
71
+ | `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) |
72
+ | `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) |
73
+ | `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) |
74
+ | `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` |
75
+ | `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) |
76
+
77
+ `running_kernel` carries the full build including the update revision
78
+ (`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
79
+ matching has to compare against.
80
+
81
+ Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V.
82
+ See netork#300 for the plan.
83
+
84
+ ## Preparing a host
85
+
86
+ WinRM is on by default on Windows Server; on Windows 10/11 run
87
+ `Enable-PSRemoting` once. Then either
88
+
89
+ * **HTTPS (5986, default)** — needs a certificate-backed HTTPS listener, or
90
+ * **HTTP (5985)** — set the device port to 5985. Traffic is still encrypted at
91
+ message level (NTLM/Kerberos), credentials never travel in the clear.
92
+
93
+ A **local** administrator account additionally needs
94
+ `LocalAccountTokenFilterPolicy = 1` under
95
+ `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`; without it
96
+ remote UAC strips the admin token. Domain accounts are not affected.
97
+
98
+ ## optional_args
99
+
100
+ | Key | Default | Meaning |
101
+ |---|---|---|
102
+ | `port` | `5986` | WinRM port |
103
+ | `winrm_ssl` | `port != 5985` | force HTTPS on or off |
104
+ | `winrm_auth` | `negotiate` | pypsrp auth protocol (`negotiate`, `ntlm`, `kerberos`, `credssp`, `basic`) |
105
+ | `ssl_verify` | `True` | validate the WinRM certificate |
106
+
107
+ ## Development
108
+
109
+ The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
110
+
111
+ ```bash
112
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
113
+ .venv/bin/pytest --cov
114
+ ```
115
+
116
+ ## Tests and fixtures
117
+
118
+ `tests/fixtures/synthetic/` holds the JSON the scripts are *designed* to emit.
119
+ To record the real thing from a host:
120
+
121
+ ```bash
122
+ python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure]
123
+ ```
124
+
125
+ Output lands in `tools/harvest-out/` (gitignored); scrub it before copying
126
+ anything into `tests/`.
127
+
128
+ ## License
129
+
130
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,95 @@
1
+ # napalm-windows
2
+
3
+ NAPALM driver for Windows Server 2016+ and Windows 10/11, part of the netOrk
4
+ driver family built on [`napalm-device-types`](https://git.netork.io/NAPALM/napalm-device-types).
5
+
6
+ Driver name: `windows` · Role: `OSDriver` · Transport: PowerShell Remoting
7
+ (PSRP) over WinRM via [`pypsrp`](https://pypi.org/project/pypsrp/).
8
+
9
+ ## Tested against
10
+
11
+ Not recorded yet: the fixtures under `tests/fixtures/synthetic/` are the JSON the scripts
12
+ are designed to emit, not output recorded from a host.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install napalm-windows
18
+ ```
19
+
20
+ ## How it works
21
+
22
+ Every getter sends one PowerShell script. The script projects the cmdlet
23
+ results onto flat, primitive fields and ends in `ConvertTo-Json`, so the
24
+ Python side parses JSON, never text. All device I/O goes through a single
25
+ seam (`PsrpTransport.run(script) -> str`), which is what the tests replace.
26
+
27
+ One runspace pool stays open per connection, so a poll pays the WinRM
28
+ handshake once.
29
+
30
+ ## Supported
31
+
32
+ | Method | Source |
33
+ |---|---|
34
+ | `get_facts` | `Win32_ComputerSystem`, `Win32_OperatingSystem`, `Win32_BIOS`, registry (`DisplayVersion`, `UBR`) |
35
+ | `get_interfaces` | `Get-NetAdapter` |
36
+ | `get_interfaces_ip` | `Get-NetIPAddress` (loopback dropped, IPv6 zone index stripped) |
37
+ | `get_arp_table` | `Get-NetNeighbor -AddressFamily IPv4` (broadcast, multicast, unreachable dropped) |
38
+ | `get_route_to` | `Get-NetRoute` (multicast, broadcast, loopback dropped) |
39
+ | `get_services` / `manage_service` | `Win32_Service`, `Start-/Stop-/Restart-Service`, `Set-Service -StartupType` |
40
+ | `get_listening_sockets` | `Get-NetTCPConnection -State Listen`, `Get-NetUDPEndpoint`, `Get-Process`, `Win32_Service` (a shared svchost names no service) |
41
+
42
+ `running_kernel` carries the full build including the update revision
43
+ (`10.0.20348.2340`): Windows ships fixes as UBR bumps, which is what CVE
44
+ matching has to compare against.
45
+
46
+ Not yet: packages, Windows Update, scheduled tasks, health metrics, Hyper-V.
47
+ See netork#300 for the plan.
48
+
49
+ ## Preparing a host
50
+
51
+ WinRM is on by default on Windows Server; on Windows 10/11 run
52
+ `Enable-PSRemoting` once. Then either
53
+
54
+ * **HTTPS (5986, default)** — needs a certificate-backed HTTPS listener, or
55
+ * **HTTP (5985)** — set the device port to 5985. Traffic is still encrypted at
56
+ message level (NTLM/Kerberos), credentials never travel in the clear.
57
+
58
+ A **local** administrator account additionally needs
59
+ `LocalAccountTokenFilterPolicy = 1` under
60
+ `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System`; without it
61
+ remote UAC strips the admin token. Domain accounts are not affected.
62
+
63
+ ## optional_args
64
+
65
+ | Key | Default | Meaning |
66
+ |---|---|---|
67
+ | `port` | `5986` | WinRM port |
68
+ | `winrm_ssl` | `port != 5985` | force HTTPS on or off |
69
+ | `winrm_auth` | `negotiate` | pypsrp auth protocol (`negotiate`, `ntlm`, `kerberos`, `credssp`, `basic`) |
70
+ | `ssl_verify` | `True` | validate the WinRM certificate |
71
+
72
+ ## Development
73
+
74
+ The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
75
+
76
+ ```bash
77
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
78
+ .venv/bin/pytest --cov
79
+ ```
80
+
81
+ ## Tests and fixtures
82
+
83
+ `tests/fixtures/synthetic/` holds the JSON the scripts are *designed* to emit.
84
+ To record the real thing from a host:
85
+
86
+ ```bash
87
+ python tools/harvest.py <host> <user> <label> [--port 5985] [--insecure]
88
+ ```
89
+
90
+ Output lands in `tools/harvest-out/` (gitignored); scrub it before copying
91
+ anything into `tests/`.
92
+
93
+ ## License
94
+
95
+ Apache-2.0, see [LICENSE](LICENSE).
@@ -0,0 +1,5 @@
1
+ """NAPALM driver for Windows hosts via PowerShell Remoting (WinRM)."""
2
+
3
+ from napalm_windows.windows import WindowsDriver
4
+
5
+ __all__ = ["WindowsDriver"]
File without changes
@@ -0,0 +1,122 @@
1
+ """PowerShell Remoting (PSRP) over WinRM — the driver's only path to the host.
2
+
3
+ One runspace pool stays open for the lifetime of the connection, so a poll
4
+ that sends a dozen scripts pays the WinRM handshake once. Everything the
5
+ driver knows about pypsrp lives in this module; the driver itself sees a
6
+ ``run(script) -> str`` seam, which is what its tests replace and what an SSH
7
+ transport (Windows OpenSSH) would implement later.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+
14
+ import requests
15
+ from napalm.base.exceptions import ConnectionClosedException, ConnectionException
16
+ from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
17
+ from pypsrp.powershell import PowerShell, RunspacePool
18
+ from pypsrp.wsman import WSMan
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class PowerShellError(Exception):
24
+ """A script ran but wrote to PowerShell's error stream."""
25
+
26
+
27
+ class PsrpTransport:
28
+ def __init__(
29
+ self,
30
+ host: str,
31
+ username: str,
32
+ password: str,
33
+ *,
34
+ port: int,
35
+ ssl: bool,
36
+ cert_validation: bool,
37
+ auth: str,
38
+ timeout: int,
39
+ ) -> None:
40
+ self.host = host
41
+ self.username = username
42
+ self._password = password
43
+ self.port = port
44
+ self.ssl = ssl
45
+ self.cert_validation = cert_validation
46
+ self.auth = auth
47
+ self.timeout = timeout
48
+ self._wsman: WSMan | None = None
49
+ self._pool: RunspacePool | None = None
50
+
51
+ def __repr__(self) -> str:
52
+ scheme = "https" if self.ssl else "http"
53
+ return f"<PsrpTransport {self.username}@{scheme}://{self.host}:{self.port}>"
54
+
55
+ @property
56
+ def is_open(self) -> bool:
57
+ return self._pool is not None
58
+
59
+ def open(self) -> None:
60
+ # encryption="auto" gives message-level encryption on plain HTTP when
61
+ # the auth protocol supports it (NTLM/Kerberos), so 5985 does not mean
62
+ # credentials or output travel in the clear.
63
+ self._wsman = WSMan(
64
+ self.host,
65
+ port=self.port,
66
+ username=self.username,
67
+ password=self._password,
68
+ ssl=self.ssl,
69
+ auth=self.auth,
70
+ cert_validation=self.cert_validation,
71
+ connection_timeout=self.timeout,
72
+ read_timeout=self.timeout,
73
+ operation_timeout=max(self.timeout - 10, 20),
74
+ encryption="auto",
75
+ )
76
+ pool = RunspacePool(self._wsman)
77
+ try:
78
+ pool.open()
79
+ except AuthenticationError as exc:
80
+ self._drop()
81
+ raise ConnectionException(f"Authentication failed for {self.username}: {exc}") from exc
82
+ except WinRMTransportError as exc:
83
+ self._drop()
84
+ if exc.code == 401:
85
+ raise ConnectionException(
86
+ f"Authentication failed for {self.username}: HTTP 401"
87
+ ) from exc
88
+ raise ConnectionException(f"WinRM error from {self.host}:{self.port}: {exc}") from exc
89
+ except (requests.RequestException, WinRMError, OSError) as exc:
90
+ self._drop()
91
+ raise ConnectionException(
92
+ f"Cannot reach WinRM on {self.host}:{self.port}: {exc}"
93
+ ) from exc
94
+ self._pool = pool
95
+
96
+ def run(self, script: str) -> str:
97
+ if self._pool is None:
98
+ raise ConnectionClosedException("WinRM connection is not open")
99
+ ps = PowerShell(self._pool)
100
+ ps.add_script(script)
101
+ output = ps.invoke()
102
+ if ps.had_errors:
103
+ message = "; ".join(str(e) for e in ps.streams.error).strip()
104
+ raise PowerShellError(message or "PowerShell reported an error")
105
+ return "\n".join(str(o) for o in output if o is not None)
106
+
107
+ def close(self) -> None:
108
+ if self._pool is not None:
109
+ try:
110
+ self._pool.close()
111
+ except Exception: # a dead connection is closed enough
112
+ logger.debug("Closing runspace pool on %s failed", self.host, exc_info=True)
113
+ self._drop()
114
+
115
+ def _drop(self) -> None:
116
+ if self._wsman is not None:
117
+ try:
118
+ self._wsman.close()
119
+ except Exception:
120
+ logger.debug("Closing WSMan session on %s failed", self.host, exc_info=True)
121
+ self._wsman = None
122
+ self._pool = None