Debian Codegraph @

lib/ansible/plugins/shell/cmd.py

raw
1 # Copyright (c) 2019 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3 from __future__ import annotations
4
5 DOCUMENTATION = """
6 name: cmd
7 version_added: '2.8'
8 short_description: Windows Command Prompt
9 description:
10 - Used with the 'winrm' connection or 'ssh' with no C(DefaultShell) set on the Windows host.
11 extends_documentation_fragment:
12 - shell_windows
13 """
14
15 import re
16
17 from ansible.plugins.shell.powershell import ShellModule as PSShellModule
18
19 # these are the metachars that have a special meaning in cmd that we want to escape when quoting
20 _find_unsafe = re.compile(r'[\s\(\)\%\!^\"\<\>\&\|]').search
21
22
23 class ShellModule(PSShellModule):
24
25 # Common shell filenames that this plugin handles
26 COMPATIBLE_SHELLS = frozenset() # type: frozenset[str]
27 # Family of shells this has. Must match the filename without extension
28 SHELL_FAMILY = 'cmd'
29
30 _SHELL_REDIRECT_ALLNULL = '>nul 2>&1'
31 _SHELL_AND = '&&'
32
33 # Used by various parts of Ansible to do Windows specific changes
34 _IS_WINDOWS = True
35
36 def join(self, cmd_parts: list[str]) -> str:
37 if not cmd_parts:
38 return ""
39
40 cmd = self._quote_argument(cmd_parts[0], for_first_argument=True)
41 args = []
42 if len(cmd_parts) > 1:
43 args = [self.quote(a) for a in cmd_parts[1:]]
44
45 args.insert(0, cmd)
46 return " ".join(args)
47
48 def quote(self, cmd: str) -> str:
49 return self._quote_argument(cmd, for_first_argument=False)
50
51 def _quote_argument(self, cmd: str, for_first_argument: bool = False) -> str:
52 # cmd does not support single quotes that the shlex_quote uses. We need to override the quoting behaviour to
53 # better match cmd.exe.
54 # https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
55
56 # Return an empty argument
57 if not cmd:
58 return '""'
59
60 if _find_unsafe(cmd) is None:
61 return cmd
62
63 # Escape the metachars as we are quoting the string to stop cmd from interpreting that metachar. For example
64 # 'file &whoami.exe' would result in 'file $(whoami.exe)' instead of the literal string
65 # https://stackoverflow.com/questions/3411771/multiple-character-replace-with-python
66 for c in '^()%!"<>&|': # '^' must be the first char that we scan and replace
67 if c in cmd:
68 # I can't find any docs that explicitly say this but to escape ", it needs to be prefixed with \^.
69 cmd = cmd.replace(c, ("\\^" if c == '"' else "^") + c)
70
71 return f'"{cmd}"' if for_first_argument else f'^"{cmd}^"'