-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathprocess.py
159 lines (127 loc) · 4.8 KB
/
process.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, Jordan Borean (@jborean93) <[email protected]>
# MIT License (see LICENSE or https://opensource.org/licenses/MIT)
import asyncio
import logging
import subprocess
import typing as t
from psrpcore import ClientRunspacePool
from psrp._connection.connection import (
AsyncEventCallable,
ConnectionInfo,
SyncEventCallable,
)
from psrp._connection.out_of_proc import (
AsyncOutOfProcConnection,
SyncOutOfProcConnection,
)
log = logging.getLogger(__name__)
class ProcessInfo(ConnectionInfo):
"""ConnectionInfo for a Process.
ConnectionInfo implementation for a native process. The data is read from
the ``stdout`` pipe of the process and the input is read to the ``stdin``
pipe. This can be used to create a Runspace Pool on a local PowerShell
instance or any other process that can handle the raw PSRP OutOfProc
messages.
When targeting Windows PowerShell (`executable='powershell'`) the arguments
must be set to `arguments='-Version 5.1 -NoProfile -ServerMode'`. The
`-Version` entry is cruical to not running in version 2.0 compatibility
mode.
Args:
executable: The executable to run, defaults to `pwsh`.
arguments: A list of arguments to run, when the executable is `pwsh`
then this defaults to `-NoProfile -NoLogo -ServerMode`.
"""
def __init__(
self,
executable: str = "pwsh",
arguments: t.Optional[t.List[str]] = None,
) -> None:
self.executable = executable
self.arguments = arguments or []
if arguments is None:
self.arguments = ["-NoProfile", "-NoLogo", "-ServerMode"]
def create_sync(
self,
pool: ClientRunspacePool,
callback: SyncEventCallable,
) -> "SyncProcessConnection":
arguments = [self.executable]
arguments.extend(self.arguments)
process = subprocess.Popen(
arguments,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0,
)
return SyncProcessConnection(pool, callback, process)
async def create_async(
self,
pool: ClientRunspacePool,
callback: AsyncEventCallable,
) -> "AsyncProcessConnection":
process = await asyncio.create_subprocess_exec(
self.executable,
*self.arguments,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
limit=32_768,
)
return AsyncProcessConnection(pool, callback, process)
class SyncProcessConnection(SyncOutOfProcConnection):
"""Synchronous Process Connection."""
def __init__(
self,
pool: ClientRunspacePool,
callback: SyncEventCallable,
process: subprocess.Popen,
) -> None:
super().__init__(pool, callback)
self._process = process
def read(self) -> t.Optional[bytes]:
data = self._process.stdout.read(self.get_fragment_size()) or None # type: ignore[union-attr] # Will be set
if log.isEnabledFor(logging.DEBUG): # pragma: no cover
log.debug("%s read %s", type(self).__name__, (data or b"").decode())
return data
def write(
self,
data: bytes,
) -> None:
if log.isEnabledFor(logging.DEBUG): # pragma: no cover
log.debug("%s write %s", type(self).__name__, data.decode())
writer: t.IO[t.Any] = self._process.stdin # type: ignore[assignment] # Will be set
writer.write(data)
writer.flush()
def stop(self) -> None:
if self._process.poll() is None:
self._process.terminate()
self._process.wait()
class AsyncProcessConnection(AsyncOutOfProcConnection):
"""Asynchronous Process Connection."""
def __init__(
self,
pool: ClientRunspacePool,
callback: AsyncEventCallable,
process: asyncio.subprocess.Process,
) -> None:
super().__init__(pool, callback)
self._process = process
async def read(self) -> t.Optional[bytes]:
data = await self._process.stdout.read(32_768) or None # type: ignore[union-attr] # Will be set
if log.isEnabledFor(logging.DEBUG): # pragma: no cover
log.debug("%s read %s", type(self).__name__, (data or b"").decode())
return data
async def write(
self,
data: bytes,
) -> None:
if log.isEnabledFor(logging.DEBUG): # pragma: no cover
log.debug("%s write %s", type(self).__name__, data.decode())
writer: asyncio.StreamWriter = self._process.stdin # type: ignore[assignment] # Will be set
writer.write(data)
await writer.drain()
async def stop(self) -> None:
self._process.terminate()
await self._process.wait()