Debian Codegraph @

lib/ansible/plugins/cliconf/__init__.py

raw
1 #
2 # (c) 2017 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 annotations
20
21 from abc import abstractmethod
22 from functools import wraps
23
24 from ansible.plugins import AnsiblePlugin
25 from ansible.errors import AnsibleError, AnsibleConnectionFailure
26 from ansible.module_utils.common.text.converters import to_bytes, to_text
27
28 try:
29 from scp import SCPClient
30 HAS_SCP = True
31 except ImportError:
32 HAS_SCP = False
33
34
35 def enable_mode(func):
36 @wraps(func)
37 def wrapped(self, *args, **kwargs):
38 prompt = self._connection.get_prompt()
39 if not to_text(prompt, errors='surrogate_or_strict').strip().endswith('#'):
40 raise AnsibleError('operation requires privilege escalation')
41 return func(self, *args, **kwargs)
42 return wrapped
43
44
45 class CliconfBase(AnsiblePlugin):
46 """
47 A base class for implementing cli connections
48
49 .. note:: String inputs to :meth:`send_command` will be cast to byte strings
50 within this method and as such are not required to be made byte strings
51 beforehand. Please avoid using literal byte strings (``b'string'``) in
52 :class:`CliConfBase` plugins as this can lead to unexpected errors when
53 running on Python 3
54
55 List of supported rpc's:
56 :get_config: Retrieves the specified configuration from the device
57 :edit_config: Loads the specified commands into the remote device
58 :get: Execute specified command on remote device
59 :get_capabilities: Retrieves device information and supported rpc methods
60 :commit: Load configuration from candidate to running
61 :discard_changes: Discard changes to candidate datastore
62
63 Note: List of supported rpc's for remote device can be extracted from
64 output of get_capabilities()
65
66 :returns: Returns output received from remote device as byte string
67
68 Usage:
69 from ansible.module_utils.connection import Connection
70
71 conn = Connection()
72 conn.get('show lldp neighbors detail')
73 conn.get_config('running')
74 conn.edit_config(['hostname test', 'netconf ssh'])
75 """
76
77 __rpc__ = ['get_config', 'edit_config', 'get_capabilities', 'get', 'enable_response_logging', 'disable_response_logging']
78
79 def __init__(self, connection):
80 super(CliconfBase, self).__init__()
81 self._connection = connection
82 self.history = list()
83 self.response_logging = False
84
85 def _alarm_handler(self, signum, frame):
86 """Alarm handler raised in case of command timeout """
87 self._connection.queue_message('log', 'closing shell due to command timeout (%s seconds).' % self._connection._play_context.timeout)
88 self.close()
89
90 def send_command(self, command=None, prompt=None, answer=None, sendonly=False, newline=True, prompt_retry_check=False, check_all=False):
91 """Executes a command over the device connection
92
93 This method will execute a command over the device connection and
94 return the results to the caller. This method will also perform
95 logging of any commands based on the `nolog` argument.
96
97 :param command: The command to send over the connection to the device
98 :param prompt: A single regex pattern or a sequence of patterns to evaluate the expected prompt from the command
99 :param answer: The answer to respond with if the prompt is matched.
100 :param sendonly: Bool value that will send the command but not wait for a result.
101 :param newline: Bool value that will append the newline character to the command
102 :param prompt_retry_check: Bool value for trying to detect more prompts
103 :param check_all: Bool value to indicate if all the values in prompt sequence should be matched or any one of
104 given prompt.
105 :returns: The output from the device after executing the command
106 """
107 kwargs = {
108 'command': to_bytes(command),
109 'sendonly': sendonly,
110 'newline': newline,
111 'prompt_retry_check': prompt_retry_check,
112 'check_all': check_all
113 }
114
115 if prompt is not None:
116 if isinstance(prompt, list):
117 kwargs['prompt'] = [to_bytes(p) for p in prompt]
118 else:
119 kwargs['prompt'] = to_bytes(prompt)
120 if answer is not None:
121 if isinstance(answer, list):
122 kwargs['answer'] = [to_bytes(p) for p in answer]
123 else:
124 kwargs['answer'] = to_bytes(answer)
125
126 resp = self._connection.send(**kwargs)
127
128 if not self.response_logging:
129 self.history.append(('*****', '*****'))
130 else:
131 self.history.append((kwargs['command'], resp))
132
133 return resp
134
135 def get_base_rpc(self):
136 """Returns list of base rpc method supported by remote device"""
137 return self.__rpc__
138
139 def get_history(self):
140 """ Returns the history file for all commands
141
142 This will return a log of all the commands that have been sent to
143 the device and all of the output received. By default, all commands
144 and output will be redacted unless explicitly configured otherwise.
145
146 :return: An ordered list of command, output pairs
147 """
148 return self.history
149
150 def reset_history(self):
151 """ Resets the history of run commands
152 :return: None
153 """
154 self.history = list()
155
156 def enable_response_logging(self):
157 """Enable logging command response"""
158 self.response_logging = True
159
160 def disable_response_logging(self):
161 """Disable logging command response"""
162 self.response_logging = False
163
164 @abstractmethod
165 def get_config(self, source='running', flags=None, format=None):
166 """Retrieves the specified configuration from the device
167
168 This method will retrieve the configuration specified by source and
169 return it to the caller as a string. Subsequent calls to this method
170 will retrieve a new configuration from the device
171
172 :param source: The configuration source to return from the device.
173 This argument accepts either `running` or `startup` as valid values.
174
175 :param flags: For devices that support configuration filtering, this
176 keyword argument is used to filter the returned configuration.
177 The use of this keyword argument is device dependent and will be
178 silently ignored on devices that do not support it.
179
180 :param format: For devices that support fetching different configuration
181 format, this keyword argument is used to specify the format in which
182 configuration is to be retrieved.
183
184 :return: The device configuration as specified by the source argument.
185 """
186 pass
187
188 @abstractmethod
189 def edit_config(self, candidate=None, commit=True, replace=None, diff=False, comment=None):
190 """Loads the candidate configuration into the network device
191
192 This method will load the specified candidate config into the device
193 and merge with the current configuration unless replace is set to
194 True. If the device does not support config replace an errors
195 is returned.
196
197 :param candidate: The configuration to load into the device and merge
198 with the current running configuration
199
200 :param commit: Boolean value that indicates if the device candidate
201 configuration should be pushed in the running configuration or discarded.
202
203 :param replace: If the value is True/False it indicates if running configuration should be completely
204 replace by candidate configuration. If can also take configuration file path as value,
205 the file in this case should be present on the remote host in the mentioned path as a
206 prerequisite.
207 :param comment: Commit comment provided it is supported by remote host
208 :return: Returns a json string with contains configuration applied on remote host, the returned
209 response on executing configuration commands and platform relevant data.
210 {
211 "diff": "",
212 "response": [],
213 "request": []
214 }
215
216 """
217 pass
218
219 @abstractmethod
220 def get(self, command=None, prompt=None, answer=None, sendonly=False, newline=True, output=None, check_all=False):
221 """Execute specified command on remote device
222 This method will retrieve the specified data and
223 return it to the caller as a string.
224 :param command: command in string format to be executed on remote device
225 :param prompt: the expected prompt generated by executing command, this can
226 be a string or a list of strings
227 :param answer: the string to respond to the prompt with
228 :param sendonly: bool to disable waiting for response, default is false
229 :param newline: bool to indicate if newline should be added at end of answer or not
230 :param output: For devices that support fetching command output in different
231 format, this keyword argument is used to specify the output in which
232 response is to be retrieved.
233 :param check_all: Bool value to indicate if all the values in prompt sequence should be matched or any one of
234 given prompt.
235 :return: The output from the device after executing the command
236 """
237 pass
238
239 @abstractmethod
240 def get_capabilities(self):
241 """Returns the basic capabilities of the network device
242 This method will provide some basic facts about the device and
243 what capabilities it has to modify the configuration. The minimum
244 return from this method takes the following format.
245 eg:
246 {
247
248 'rpc': [list of supported rpcs],
249 'network_api': <str>, # the name of the transport
250 'device_info': {
251 'network_os': <str>,
252 'network_os_version': <str>,
253 'network_os_model': <str>,
254 'network_os_hostname': <str>,
255 'network_os_image': <str>,
256 'network_os_platform': <str>,
257 },
258 'device_operations': {
259 'supports_diff_replace': <bool>, # identify if config should be merged or replaced is supported
260 'supports_commit': <bool>, # identify if commit is supported by device or not
261 'supports_rollback': <bool>, # identify if rollback is supported or not
262 'supports_defaults': <bool>, # identify if fetching running config with default is supported
263 'supports_commit_comment': <bool>, # identify if adding comment to commit is supported of not
264 'supports_onbox_diff': <bool>, # identify if on box diff capability is supported or not
265 'supports_generate_diff': <bool>, # identify if diff capability is supported within plugin
266 'supports_multiline_delimiter': <bool>, # identify if multiline delimiter is supported within config
267 'supports_diff_match': <bool>, # identify if match is supported
268 'supports_diff_ignore_lines': <bool>, # identify if ignore line in diff is supported
269 'supports_config_replace': <bool>, # identify if running config replace with candidate config is supported
270 'supports_admin': <bool>, # identify if admin configure mode is supported or not
271 'supports_commit_label': <bool>, # identify if commit label is supported or not
272 }
273 'format': [list of supported configuration format],
274 'diff_match': [list of supported match values],
275 'diff_replace': [list of supported replace values],
276 'output': [list of supported command output format]
277 }
278 :return: capability as dict
279 """
280 result = {}
281 result['rpc'] = self.get_base_rpc()
282 result['device_info'] = self.get_device_info()
283 result['network_api'] = 'cliconf'
284 return result
285
286 @abstractmethod
287 def get_device_info(self):
288 """Returns basic information about the network device.
289
290 This method will provide basic information about the device such as OS version and model
291 name. This data is expected to be used to fill the 'device_info' key in get_capabilities()
292 above.
293
294 :return: dictionary of device information
295 """
296 pass
297
298 def commit(self, comment=None):
299 """Commit configuration changes
300
301 This method will perform the commit operation on a previously loaded
302 candidate configuration that was loaded using `edit_config()`. If
303 there is a candidate configuration, it will be committed to the
304 active configuration. If there is not a candidate configuration, this
305 method should just silently return.
306
307 :return: None
308 """
309 return self._connection.method_not_found("commit is not supported by network_os %s" % self._play_context.network_os)
310
311 def discard_changes(self):
312 """Discard candidate configuration
313
314 This method will discard the current candidate configuration if one
315 is present. If there is no candidate configuration currently loaded,
316 then this method should just silently return
317
318 :returns: None
319 """
320 return self._connection.method_not_found("discard_changes is not supported by network_os %s" % self._play_context.network_os)
321
322 def rollback(self, rollback_id, commit=True):
323 """
324
325 :param rollback_id: The commit id to which configuration should be rollbacked
326 :param commit: Flag to indicate if changes should be committed or not
327 :return: Returns diff between before and after change.
328 """
329 pass
330
331 def copy_file(self, source=None, destination=None, proto='scp', timeout=30):
332 """Copies file over scp/sftp to remote device
333
334 :param source: Source file path
335 :param destination: Destination file path on remote device
336 :param proto: Protocol to be used for file transfer,
337 supported protocol: scp and sftp
338 :param timeout: Specifies the wait time to receive response from
339 remote host before triggering timeout exception
340 :return: None
341 """
342 ssh = self._connection.paramiko_conn._connect_uncached()
343 if proto == 'scp':
344 if not HAS_SCP:
345 raise AnsibleError("Required library scp is not installed. Please install it using `pip install scp`")
346 with SCPClient(ssh.get_transport(), socket_timeout=timeout) as scp:
347 out = scp.put(source, destination)
348 elif proto == 'sftp':
349 with ssh.open_sftp() as sftp:
350 sftp.put(source, destination)
351
352 def get_file(self, source=None, destination=None, proto='scp', timeout=30):
353 """Fetch file over scp/sftp from remote device
354 :param source: Source file path
355 :param destination: Destination file path
356 :param proto: Protocol to be used for file transfer,
357 supported protocol: scp and sftp
358 :param timeout: Specifies the wait time to receive response from
359 remote host before triggering timeout exception
360 :return: None
361 """
362 ssh = self._connection.paramiko_conn._connect_uncached()
363 if proto == 'scp':
364 if not HAS_SCP:
365 raise AnsibleError("Required library scp is not installed. Please install it using `pip install scp`")
366 try:
367 with SCPClient(ssh.get_transport(), socket_timeout=timeout) as scp:
368 scp.get(source, destination)
369 except EOFError:
370 # This appears to be benign.
371 pass
372 elif proto == 'sftp':
373 with ssh.open_sftp() as sftp:
374 sftp.get(source, destination)
375
376 def get_diff(self, candidate=None, running=None, diff_match=None, diff_ignore_lines=None, path=None, diff_replace=None):
377 """
378 Generate diff between candidate and running configuration. If the
379 remote host supports onbox diff capabilities ie. supports_onbox_diff in that case
380 candidate and running configurations are not required to be passed as argument.
381 In case if onbox diff capability is not supported candidate argument is mandatory
382 and running argument is optional.
383 :param candidate: The configuration which is expected to be present on remote host.
384 :param running: The base configuration which is used to generate diff.
385 :param diff_match: Instructs how to match the candidate configuration with current device configuration
386 Valid values are 'line', 'strict', 'exact', 'none'.
387 'line' - commands are matched line by line
388 'strict' - command lines are matched with respect to position
389 'exact' - command lines must be an equal match
390 'none' - will not compare the candidate configuration with the running configuration
391 :param diff_ignore_lines: Use this argument to specify one or more lines that should be
392 ignored during the diff. This is used for lines in the configuration
393 that are automatically updated by the system. This argument takes
394 a list of regular expressions or exact line matches.
395 :param path: The ordered set of parents that uniquely identify the section or hierarchy
396 the commands should be checked against. If the parents argument
397 is omitted, the commands are checked against the set of top
398 level or global commands.
399 :param diff_replace: Instructs on the way to perform the configuration on the device.
400 If the replace argument is set to I(line) then the modified lines are
401 pushed to the device in configuration mode. If the replace argument is
402 set to I(block) then the entire command block is pushed to the device in
403 configuration mode if any line is not correct.
404 :return: Configuration and/or banner diff in json format.
405 {
406 'config_diff': ''
407 }
408
409 """
410 pass
411
412 def run_commands(self, commands=None, check_rc=True):
413 """
414 Execute a list of commands on remote host and return the list of response
415 :param commands: The list of command that needs to be executed on remote host.
416 The individual command in list can either be a command string or command dict.
417 If the command is dict the valid keys are
418 {
419 'command': <command to be executed>
420 'prompt': <expected prompt on executing the command>,
421 'answer': <answer for the prompt>,
422 'output': <the format in which command output should be rendered eg: 'json', 'text'>,
423 'sendonly': <Boolean flag to indicate if it command execution response should be ignored or not>
424 }
425 :param check_rc: Boolean flag to check if returned response should be checked for error or not.
426 If check_rc is False the error output is appended in return response list, else if the
427 value is True an exception is raised.
428 :return: List of returned response
429 """
430 pass
431
432 def check_edit_config_capability(self, operations, candidate=None, commit=True, replace=None, comment=None):
433
434 if not candidate and not replace:
435 raise ValueError("must provide a candidate or replace to load configuration")
436
437 if commit not in (True, False):
438 raise ValueError("'commit' must be a bool, got %s" % commit)
439
440 if replace and not operations['supports_replace']:
441 raise ValueError("configuration replace is not supported")
442
443 if comment and not operations.get('supports_commit_comment', False):
444 raise ValueError("commit comment is not supported")
445
446 if replace and not operations.get('supports_replace', False):
447 raise ValueError("configuration replace is not supported")
448
449 def set_cli_prompt_context(self):
450 """
451 Ensure the command prompt on device is in right mode
452 :return: None
453 """
454 pass
455
456 def _update_cli_prompt_context(self, config_context=None, exit_command='exit'):
457 """
458 Update the cli prompt context to ensure it is in operational mode
459 :param config_context: It is string value to identify if the current cli prompt ends with config mode prompt
460 :param exit_command: Command to execute to exit the config mode
461 :return: None
462 """
463 out = self._connection.get_prompt()
464 if out is None:
465 raise AnsibleConnectionFailure(message=u'cli prompt is not identified from the last received'
466 u' response window: %s' % self._connection._last_recv_window)
467
468 while True:
469 out = to_text(out, errors='surrogate_then_replace').strip()
470 if config_context and out.endswith(config_context):
471 self._connection.queue_message('vvvv', 'wrong context, sending exit to device')
472 self.send_command(exit_command)
473 out = self._connection.get_prompt()
474 else:
475 break