Debian Codegraph @

ansible_collections/cisco/nxos/plugins/terminal/nxos.py

raw
1 #
2 # (c) 2016 Red Hat Inc.
3 #
4 # This file is part of Ansible
5 #
6 # Ansible is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Ansible is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
18 #
19 from __future__ import absolute_import, division, print_function
20
21
22 __metaclass__ = type
23
24 import json
25 import re
26
27 from ansible.errors import AnsibleConnectionFailure
28 from ansible.module_utils._text import to_bytes, to_text
29 from ansible_collections.ansible.netcommon.plugins.plugin_utils.terminal_base import TerminalBase
30
31
32 class TerminalModule(TerminalBase):
33 terminal_stdout_re = [
34 re.compile(
35 rb"[\r\n](?!\s*<)?(\x1b\S+)*[a-zA-Z_0-9]{1}[a-zA-Z0-9-_.]*[>|#](?:\s*)(\x1b\S+)*$",
36 ),
37 re.compile(rb"[\r\n]?[a-zA-Z0-9]{1}[a-zA-Z0-9-_.]*\(.+\)#(?:\s*)$"),
38 ]
39
40 terminal_stderr_re = [
41 re.compile(rb"% ?Error"),
42 re.compile(rb"\nerror:(.*)", re.I),
43 re.compile(rb"^% \w+", re.M),
44 re.compile(rb"% ?Bad secret"),
45 re.compile(rb"invalid input", re.I),
46 re.compile(rb"(?:incomplete|ambiguous) command", re.I),
47 re.compile(rb"connection timed out", re.I),
48 re.compile(rb"[^\r\n] not found", re.I),
49 re.compile(rb"'[^']' +returned error code: ?\d+"),
50 re.compile(rb"syntax error"),
51 re.compile(rb"unknown command"),
52 re.compile(rb"user not present"),
53 re.compile(rb"invalid (.+?)at '\^' marker", re.I),
54 re.compile(rb"configuration not allowed .+ at '\^' marker"),
55 re.compile(
56 rb"[B|b]aud rate of console should be.* (\d*) to increase [a-z]* level",
57 re.I,
58 ),
59 re.compile(rb"cannot apply non-existing acl policy to interface", re.I),
60 re.compile(rb"Duplicate sequence number", re.I),
61 re.compile(
62 rb"Cannot apply ACL to an interface that is a port-channel member",
63 re.I,
64 ),
65 re.compile(rb"No corresponding (.+) configured", re.I),
66 re.compile(rb"(.+)please specify sequence number", re.I),
67 re.compile(rb"(.+sufficient free entries are not available in tcam bank.*)", re.I),
68 ]
69
70 terminal_config_prompt = re.compile(r"^.*\((?!maint-mode).*\)#$")
71
72 def on_become(self, passwd=None):
73 if self._get_prompt().strip().endswith(b"#"):
74 return
75
76 out = self._exec_cli_command("show privilege")
77 out = to_text(out, errors="surrogate_then_replace").strip()
78
79 # if already at privilege level 15 return
80 if "15" in out:
81 return
82
83 if self.validate_user_role():
84 return
85
86 if "Disabled" in out:
87 raise AnsibleConnectionFailure("Feature privilege is not enabled")
88
89 cmd = {"command": "enable"}
90 if passwd:
91 cmd["prompt"] = to_text(r"(?i)[\r\n]?Password: $", errors="surrogate_or_strict")
92 cmd["answer"] = passwd
93 cmd["prompt_retry_check"] = True
94
95 try:
96 self._exec_cli_command(to_bytes(json.dumps(cmd), errors="surrogate_or_strict"))
97 prompt = self._get_prompt()
98 if prompt is None or not prompt.strip().endswith(b"enable#"):
99 raise AnsibleConnectionFailure(
100 "failed to elevate privilege to enable mode still at prompt [%s]" % prompt,
101 )
102 except AnsibleConnectionFailure as e:
103 prompt = self._get_prompt()
104 raise AnsibleConnectionFailure(
105 "unable to elevate privilege to enable mode, at prompt [%s] with error: %s"
106 % (prompt, e.message),
107 )
108
109 def on_unbecome(self):
110 prompt = self._get_prompt()
111 if prompt is None:
112 # if prompt is None most likely the terminal is hung up at a prompt
113 return
114
115 if b"(config" in prompt:
116 self._exec_cli_command("end")
117 self._exec_cli_command("exit")
118
119 elif prompt.endswith(b"enable#"):
120 self._exec_cli_command("exit")
121
122 def on_open_shell(self):
123 try:
124 for cmd in ("terminal length 0", "terminal width 511"):
125 self._exec_cli_command(cmd)
126 except AnsibleConnectionFailure:
127 raise AnsibleConnectionFailure("unable to set terminal parameters")
128
129 def validate_user_role(self):
130 user = self._connection._play_context.remote_user
131
132 out = self._exec_cli_command("show user-account %s" % user)
133 out = to_text(out, errors="surrogate_then_replace").strip()
134
135 match = re.search(r"roles:(.+)$", out, re.M)
136 if match:
137 roles = match.group(1).split()
138 if "network-admin" in roles:
139 return True
140 return False