Debian Codegraph @

lib/ansible/plugins/shell/powershell.py

raw
1 # Copyright (c) 2014, Chris Church <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 DOCUMENTATION = """
7 name: powershell
8 version_added: historical
9 short_description: Windows PowerShell
10 description:
11 - The only option when using 'winrm' or 'psrp' as a connection plugin.
12 - Can also be used when using 'ssh' as a connection plugin and the C(DefaultShell) has been configured to PowerShell.
13 extends_documentation_fragment:
14 - shell_windows
15 """
16
17 import base64
18 import os
19 import shlex
20 import ntpath
21
22 from ansible._internal._powershell import _script
23 from ansible.executor.powershell.module_manifest import _bootstrap_powershell_script
24 from ansible.module_utils.common.text.converters import to_text
25 from ansible.plugins.shell import ShellBase, _ShellCommand
26 from ansible.utils.display import Display
27
28
29 display = Display()
30
31 _common_args = ['PowerShell', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted']
32
33
34 class ShellModule(ShellBase):
35
36 # Common shell filenames that this plugin handles
37 # Powershell is handled differently. It's selected when winrm is the
38 # connection
39 COMPATIBLE_SHELLS = frozenset() # type: frozenset[str]
40 # Family of shells this has. Must match the filename without extension
41 SHELL_FAMILY = 'powershell'
42
43 # We try catch as some connection plugins don't have a console (PSRP).
44 _CONSOLE_ENCODING = "try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding } catch {}"
45 _SHELL_REDIRECT_ALLNULL = '> $null'
46 _SHELL_AND = ';'
47
48 # Used by various parts of Ansible to do Windows specific changes
49 _IS_WINDOWS = True
50
51 # TODO: add binary module support
52
53 def env_prefix(self, **kwargs):
54 # powershell/winrm env handling is handled in the exec wrapper
55 return ""
56
57 def join_path(self, *args):
58 # use normpath() to remove doubled slashed and convert forward to backslashes
59 parts = [ntpath.normpath(arg) for arg in args]
60
61 # Because ntpath.join treats any component that begins with a backslash as an absolute path,
62 # we have to strip slashes from at least the beginning, otherwise join will ignore all previous
63 # path components except for the drive.
64 return ntpath.join(parts[0], *[part.strip('\\') for part in parts[1:]])
65
66 def get_remote_filename(self, pathname):
67 # powershell requires that script files end with .ps1
68 base_name = os.path.basename(pathname.strip())
69 name, ext = os.path.splitext(base_name.strip())
70 if ext.lower() not in ['.ps1', '.exe']:
71 return name + '.ps1'
72
73 return base_name.strip()
74
75 def path_has_trailing_slash(self, path):
76 # Allow Windows paths to be specified using either slash.
77 return path.endswith('/') or path.endswith('\\')
78
79 def chmod(self, paths, mode):
80 raise NotImplementedError('chmod is not implemented for Powershell')
81
82 def chown(self, paths, user):
83 raise NotImplementedError('chown is not implemented for Powershell')
84
85 def set_user_facl(self, paths, user, mode):
86 raise NotImplementedError('set_user_facl is not implemented for Powershell')
87
88 def remove(self, path, recurse=False):
89 path = _script.quote_pwsh_argument(path)
90 script = f"Remove-Item {path} -Force"
91 if recurse:
92 script += " -Recurse"
93
94 return self._encode_pwsh_script_as_command(script)
95
96 def mkdtemp(
97 self,
98 basefile: str | None = None,
99 system: bool = False,
100 mode: int = 0o700,
101 tmpdir: str | None = None,
102 ) -> str:
103 # This is used when connection plugins do not support pipelining.
104 if not basefile:
105 basefile = self.__class__._generate_temp_dir_name()
106 basefile = _script.quote_pwsh_argument(basefile, force_quote=True)
107 basetmpdir = _script.quote_pwsh_argument(tmpdir if tmpdir else self.get_option('remote_tmp'), force_quote=True)
108
109 script = f"""
110 {self._CONSOLE_ENCODING}
111 $tmp_path = [System.Environment]::ExpandEnvironmentVariables({basetmpdir})
112 $tmp = New-Item -Type Directory -Path $tmp_path -Name {basefile}
113 Write-Output -InputObject $tmp.FullName
114 """
115 return self._encode_pwsh_script_as_command(script)
116
117 def _mkdtemp2(
118 self,
119 basefile: str | None = None,
120 system: bool = False,
121 mode: int = 0o700,
122 tmpdir: str | None = None,
123 ) -> _ShellCommand:
124 # Windows does not have an equivalent for the system temp files, so
125 # the param is ignored
126 if not basefile:
127 basefile = self.__class__._generate_temp_dir_name()
128
129 basetmpdir = tmpdir if tmpdir else self.get_option('remote_tmp')
130
131 script, stdin = _bootstrap_powershell_script("powershell_mkdtemp.ps1", {
132 'Directory': basetmpdir,
133 'Name': basefile,
134 })
135 command = self._encode_pwsh_script_as_command(script)
136
137 return _ShellCommand(
138 command=command,
139 input_data=stdin,
140 )
141
142 def expand_user(
143 self,
144 user_home_path: str,
145 username: str = '',
146 ) -> str:
147 # This is used when connection plugins do not support pipelining.
148
149 script = self._CONSOLE_ENCODING
150 if user_home_path == '~':
151 script += "; (Get-Location).Path"
152 elif user_home_path.startswith('~\\'):
153 quoted_home = _script.quote_pwsh_argument(user_home_path[1:], force_quote=True)
154 script += f"; ((Get-Location).Path + {quoted_home})"
155 else:
156 script += f"; {_script.quote_pwsh_argument(user_home_path, force_quote=True)}"
157
158 return self._encode_pwsh_script_as_command(script)
159
160 def _expand_user2(
161 self,
162 user_home_path: str,
163 username: str = '',
164 ) -> _ShellCommand:
165 script, stdin = _bootstrap_powershell_script("powershell_expand_user.ps1", {
166 'Path': user_home_path,
167 })
168 command = self._encode_pwsh_script_as_command(script)
169
170 return _ShellCommand(
171 command=command,
172 input_data=stdin,
173 )
174
175 def exists(self, path):
176 path = _script.quote_pwsh_argument(path)
177 script = f"exit -not (Test-Path -LiteralPath {path})"
178
179 return self._encode_pwsh_script_as_command(script)
180
181 def checksum(self, path, *args, **kwargs):
182 display.deprecated(
183 msg="The `ShellModule.checksum` method is deprecated.",
184 version="2.23",
185 help_text="Use `ActionBase._execute_remote_stat()` instead.",
186 )
187 path = _script.quote_pwsh_argument(path)
188 script = """
189 If (Test-Path -PathType Leaf %(path)s)
190 {
191 $sp = new-object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider;
192 $fp = [System.IO.File]::Open(%(path)s, [System.IO.Filemode]::Open, [System.IO.FileAccess]::Read);
193 [System.BitConverter]::ToString($sp.ComputeHash($fp)).Replace("-", "").ToLower();
194 $fp.Dispose();
195 }
196 ElseIf (Test-Path -PathType Container %(path)s)
197 {
198 Write-Output "3";
199 }
200 Else
201 {
202 Write-Output "1";
203 }
204 """ % dict(path=path)
205
206 return self._encode_pwsh_script_as_command(script)
207
208 def build_module_command(self, env_string, shebang, cmd, arg_path=None):
209 # This will be called when executing modules not covered by the pwsh
210 # exec wrapper. For example module replacer, binary or basic shell
211 # modules.
212 # The env_string is never used in PowerShell.
213 cmd_parts = shlex.split(cmd, posix=False)
214
215 if shebang and shebang.startswith('#!'):
216 cmd = shebang[2:]
217 elif not shebang:
218 # The module is assumed to be a binary
219 cmd = cmd_parts.pop(0)
220
221 if arg_path:
222 cmd_parts.append(arg_path)
223
224 script = _script.build_pwsh_cmd_statement(cmd, cmd_parts)
225 return self._encode_pwsh_script_as_command(script)
226
227 def wrap_for_exec(self, cmd):
228 super().wrap_for_exec(cmd)
229 return '& %s; exit $LASTEXITCODE' % cmd
230
231 def join(self, cmd_parts: list[str]) -> str:
232 if not cmd_parts:
233 return ""
234
235 cmd = cmd_parts[0]
236 args = []
237 if len(cmd_parts) > 1:
238 args = cmd_parts[1:]
239
240 return _script.build_pwsh_cmd_statement(cmd, args)
241
242 def quote(self, cmd: str) -> str:
243 return _script.quote_pwsh_argument(cmd)
244
245 def _encode_pwsh_script_as_command(self, script: str) -> str:
246 """Wraps the provided PowerShell script as a command line string for the current shell plugin."""
247 cmd_args = _script.get_pwsh_encoded_cmdline(script, override_execution_policy=True)
248 return self.join(cmd_args)
249
250 def _encode_script(self, script, as_list=False, strict_mode=True, preserve_rc=True):
251 """Convert a PowerShell script to a single base64-encoded command."""
252 # Needs a deprecation as ansible.windows uses this in the reboot plugin.
253 display.deprecated(
254 msg="The `PowerShell._encode_script` method is deprecated.",
255 version="2.24",
256 help_text="Contact plugin author to update their plugin to use an alternative method.",
257 )
258 script = to_text(script)
259
260 if script == u'-':
261 cmd_parts = _common_args + ['-Command', '-']
262
263 else:
264 if strict_mode:
265 script = u'Set-StrictMode -Version Latest\r\n%s' % script
266 # try to propagate exit code if present- won't work with begin/process/end-style scripts (ala put_file)
267 # NB: the exit code returned may be incorrect in the case of a successful command followed by an invalid command
268 if preserve_rc:
269 script = u'%s\r\nIf (-not $?) { If (Get-Variable LASTEXITCODE -ErrorAction SilentlyContinue) { exit $LASTEXITCODE } Else { exit 1 } }\r\n'\
270 % script
271 script = '\n'.join([x.strip() for x in script.splitlines() if x.strip()])
272 encoded_script = to_text(base64.b64encode(script.encode('utf-16-le')), 'utf-8')
273 cmd_parts = _common_args + ['-EncodedCommand', encoded_script]
274
275 if as_list:
276 return cmd_parts
277 return ' '.join(cmd_parts)