Debian Codegraph @

ansible_collections/cisco/ios/plugins/terminal/ios.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.utils.display import Display
30 from ansible_collections.ansible.netcommon.plugins.plugin_utils.terminal_base import TerminalBase
31
32
33 display = Display()
34
35
36 class TerminalModule(TerminalBase):
37 terminal_stdout_re = [
38 re.compile(rb"[\r\n]?[\w\+\-\.:\/\[\]]+(?:\([^\)]+\)){0,3}(?:[>#]) ?$"),
39 ]
40
41 privilege_level_re = re.compile(r"Current privilege level is (\d+)$")
42
43 terminal_stderr_re = [
44 re.compile(rb"% ?Error"),
45 # re.compile(rb"^% \w+", re.M),
46 re.compile(rb"ERROR:", re.IGNORECASE),
47 re.compile(rb"% ?Bad secret"),
48 re.compile(rb"[\r\n%] Bad passwords"),
49 re.compile(rb"invalid input", re.I),
50 re.compile(rb"(?:incomplete|ambiguous) command", re.I),
51 re.compile(rb"connection timed out", re.I),
52 re.compile(rb"[^\r\n]+ not found"),
53 re.compile(rb"'[^']' +returned error code: ?\d+"),
54 re.compile(rb"Bad mask", re.I),
55 re.compile(rb"% ?(\S+) ?overlaps with ?(\S+)", re.I),
56 re.compile(rb"% ?(\S+) ?Error: ?[\s]+", re.I),
57 re.compile(rb"% ?(\S+) ?Informational: ?[\s]+", re.I),
58 re.compile(rb"Command authorization failed"),
59 re.compile(rb"Command Rejected(\s*\([^)]*\))?\s*: ?[\s]+", re.I),
60 re.compile(
61 rb"% General session commands not allowed under the address family",
62 re.I,
63 ),
64 re.compile(rb"% BGP: Error initializing topology", re.I),
65 re.compile(rb"%SNMP agent not enabled", re.I),
66 re.compile(rb"% Invalid", re.I),
67 re.compile(
68 rb"%You must disable VTPv1 and VTPv2 or switch to VTPv3 before configuring a VLAN name longer than 32 characters",
69 re.I,
70 ),
71 ]
72
73 terminal_config_prompt = re.compile(r"^.+\(config(-.*)?\)#$")
74
75 def get_privilege_level(self):
76 try:
77 cmd = {"command": "show privilege"}
78 result = self._exec_cli_command(
79 to_bytes(json.dumps(cmd), errors="surrogate_or_strict"),
80 )
81 except AnsibleConnectionFailure as e:
82 raise AnsibleConnectionFailure(
83 "unable to fetch privilege, with error: %s" % (e.message),
84 )
85
86 prompt = self.privilege_level_re.search(result)
87 if not prompt:
88 raise AnsibleConnectionFailure(
89 "unable to check privilege level [%s]" % result,
90 )
91
92 return int(prompt.group(1))
93
94 def on_open_shell(self):
95 _is_sdWan = False # initialize to false for default IOS execution
96 try:
97 self._exec_cli_command(b"terminal length 0")
98 except AnsibleConnectionFailure:
99 try:
100 self._exec_cli_command(b"screen-length 0") # support to SD-WAN mode
101 _is_sdWan = True
102 except AnsibleConnectionFailure: # fails as length required for handling prompt
103 raise AnsibleConnectionFailure("unable to set terminal parameters")
104 try:
105 if _is_sdWan:
106 self._exec_cli_command(b"screen-width 512") # support to SD-WAN mode
107 else:
108 self._exec_cli_command(b"terminal width 512")
109 try:
110 self._exec_cli_command(b"terminal width 0")
111 except AnsibleConnectionFailure:
112 pass
113 except AnsibleConnectionFailure:
114 display.display(
115 "WARNING: Unable to set terminal/screen width, command responses may be truncated",
116 )
117
118 def on_become(self, passwd=None):
119 if self._get_prompt().endswith(b"#") and self.get_privilege_level() == 15:
120 return
121
122 cmd = {"command": "enable"}
123 if passwd:
124 # Note: python-3.5 cannot combine u"" and r"" together. Thus make
125 # an r string and use to_text to ensure it's text on both py2 and py3.
126 cmd["prompt"] = to_text(
127 r"[\r\n]?(?:.*)?[Pp]assword: ?$",
128 errors="surrogate_or_strict",
129 )
130 cmd["answer"] = passwd
131 cmd["prompt_retry_check"] = True
132 try:
133 self._exec_cli_command(
134 to_bytes(json.dumps(cmd), errors="surrogate_or_strict"),
135 )
136 prompt = self._get_prompt()
137 privilege_level = self.get_privilege_level()
138 except AnsibleConnectionFailure as e:
139 prompt = self._get_prompt()
140 raise AnsibleConnectionFailure(
141 "failed to elevate privilege to enable mode, at prompt [%s] with error: %s"
142 % (prompt, e.message),
143 )
144
145 if prompt is None or not prompt.endswith(b"#") or privilege_level != 15:
146 raise AnsibleConnectionFailure(
147 "failed to elevate privilege to enable mode, still at level [%d] and prompt [%s]"
148 % (privilege_level, prompt),
149 )
150
151 def on_unbecome(self):
152 prompt = self._get_prompt()
153 if prompt is None:
154 # if prompt is None most likely the terminal is hung up at a prompt
155 return
156
157 if self.get_privilege_level() != 15:
158 return
159
160 if b"(config" in prompt:
161 self._exec_cli_command(b"end")
162 self._exec_cli_command(b"disable")
163
164 elif prompt.endswith(b"#"):
165 self._exec_cli_command(b"disable")