| 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 absolute_import, division, print_function |
| 20 |
|
| 21 |
|
| 22 |
__metaclass__ = type |
| 23 |
|
| 24 |
DOCUMENTATION = """ |
| 25 |
author: |
| 26 |
- Ansible Networking Team (@ansible-network) |
| 27 |
name: ios |
| 28 |
short_description: Use ios cliconf to run command on Cisco IOS platform |
| 29 |
description: |
| 30 |
- This ios plugin provides low level abstraction apis for sending and receiving CLI |
| 31 |
commands from Cisco IOS network devices. |
| 32 |
version_added: 1.0.0 |
| 33 |
options: |
| 34 |
commit_confirm_immediate: |
| 35 |
type: boolean |
| 36 |
default: false |
| 37 |
description: |
| 38 |
- Enable or disable commit confirm mode. |
| 39 |
- Confirms the configuration pushed after a custom/ default timeout.(default 1 minute). |
| 40 |
- For custom timeout configuration set commit_confirm_timeout value. |
| 41 |
- On commit_confirm_immediate default value for commit_confirm_timeout is considered 1 minute |
| 42 |
when variable in not explicitly declared. |
| 43 |
env: |
| 44 |
- name: ANSIBLE_IOS_COMMIT_CONFIRM_IMMEDIATE |
| 45 |
vars: |
| 46 |
- name: ansible_ios_commit_confirm_immediate |
| 47 |
commit_confirm_timeout: |
| 48 |
type: int |
| 49 |
description: |
| 50 |
- Commits the configuration on a trial basis for the time |
| 51 |
specified in minutes. |
| 52 |
- Using commit_confirm_timeout without specifying commit_confirm_immediate would |
| 53 |
need an explicit C(configure confirm) using the ios_command module |
| 54 |
to confirm/commit the changes made. |
| 55 |
- Refer to example for a use case demonstration. |
| 56 |
env: |
| 57 |
- name: ANSIBLE_IOS_COMMIT_CONFIRM_TIMEOUT |
| 58 |
vars: |
| 59 |
- name: ansible_ios_commit_confirm_timeout |
| 60 |
config_commands: |
| 61 |
description: |
| 62 |
- Specifies a list of commands that can make configuration changes |
| 63 |
to the target device. |
| 64 |
- When `ansible_network_single_user_mode` is enabled, if a command sent |
| 65 |
to the device is present in this list, the existing cache is invalidated. |
| 66 |
version_added: 2.0.0 |
| 67 |
type: list |
| 68 |
elements: str |
| 69 |
default: [] |
| 70 |
vars: |
| 71 |
- name: ansible_ios_config_commands |
| 72 |
""" |
| 73 |
|
| 74 |
EXAMPLES = """ |
| 75 |
# NOTE - IOS waits for a `configure confirm` when the configure terminal |
| 76 |
# command executed is `configure terminal revert timer <timeout>` within the timeout |
| 77 |
# period for the configuration to commit successfully, else a rollback |
| 78 |
# happens. |
| 79 |
|
| 80 |
# Use commit confirm with timeout and confirm the commit explicitly |
| 81 |
|
| 82 |
- name: Example commit confirmed |
| 83 |
vars: |
| 84 |
ansible_ios_commit_confirm_timeout: 1 |
| 85 |
tasks: |
| 86 |
- name: "Commit confirmed with timeout" |
| 87 |
cisco.ios.ios_hostname: |
| 88 |
state: merged |
| 89 |
config: |
| 90 |
hostname: R1 |
| 91 |
|
| 92 |
- name: "Confirm the Commit" |
| 93 |
cisco.ios.ios_command: |
| 94 |
commands: |
| 95 |
- configure confirm |
| 96 |
|
| 97 |
# Commands fired |
| 98 |
# - configure terminal revert timer 1 (cliconf specific) |
| 99 |
# - hostname R1 (from hostname resource module) |
| 100 |
# - configure confirm (from ios_command module) |
| 101 |
|
| 102 |
# Use commit confirm with timeout and confirm the commit via cliconf |
| 103 |
|
| 104 |
- name: Example commit confirmed |
| 105 |
vars: |
| 106 |
ansible_ios_commit_confirm_immediate: True |
| 107 |
ansible_ios_commit_confirm_timeout: 3 |
| 108 |
tasks: |
| 109 |
- name: "Commit confirmed with timeout" |
| 110 |
cisco.ios.ios_hostname: |
| 111 |
state: merged |
| 112 |
config: |
| 113 |
hostname: R1 |
| 114 |
|
| 115 |
# Commands fired |
| 116 |
# - configure terminal revert timer 3 (cliconf specific) |
| 117 |
# - hostname R1 (from hostname resource module) |
| 118 |
# - configure confirm (cliconf specific) |
| 119 |
|
| 120 |
# Use commit confirm via cliconf using default timeout |
| 121 |
|
| 122 |
- name: Example commit confirmed |
| 123 |
vars: |
| 124 |
ansible_ios_commit_confirm_immediate: True |
| 125 |
tasks: |
| 126 |
- name: "Commit confirmed with timeout" |
| 127 |
cisco.ios.ios_hostname: |
| 128 |
state: merged |
| 129 |
config: |
| 130 |
hostname: R1 |
| 131 |
|
| 132 |
# Commands fired |
| 133 |
# - configure terminal revert timer 1 (cliconf specific with default timeout) |
| 134 |
# - hostname R1 (from hostname resource module) |
| 135 |
# - configure confirm (cliconf specific) |
| 136 |
|
| 137 |
""" |
| 138 |
|
| 139 |
import json |
| 140 |
import re |
| 141 |
import time |
| 142 |
|
| 143 |
from ansible.errors import AnsibleConnectionFailure |
| 144 |
from ansible.module_utils._text import to_text |
| 145 |
from ansible.module_utils.common._collections_compat import Mapping |
| 146 |
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import ( |
| 147 |
NetworkConfig, |
| 148 |
dumps, |
| 149 |
) |
| 150 |
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list |
| 151 |
from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import ( |
| 152 |
CliconfBase, |
| 153 |
enable_mode, |
| 154 |
) |
| 155 |
|
| 156 |
|
| 157 |
class Cliconf(CliconfBase): |
| 158 |
def __init__(self, *args, **kwargs): |
| 159 |
self._device_info = {} |
| 160 |
super(Cliconf, self).__init__(*args, **kwargs) |
| 161 |
|
| 162 |
@enable_mode |
| 163 |
def get_config(self, source="running", flags=None, format=None): |
| 164 |
if source not in ("running", "startup"): |
| 165 |
raise ValueError("fetching configuration from %s is not supported" % source) |
| 166 |
|
| 167 |
if format: |
| 168 |
raise ValueError("'format' value %s is not supported for get_config" % format) |
| 169 |
|
| 170 |
if not flags: |
| 171 |
flags = [] |
| 172 |
if source == "running": |
| 173 |
cmd = "show running-config " |
| 174 |
else: |
| 175 |
cmd = "show startup-config " |
| 176 |
|
| 177 |
cmd += " ".join(to_list(flags)) |
| 178 |
cmd = cmd.strip() |
| 179 |
|
| 180 |
return self.send_command(cmd) |
| 181 |
|
| 182 |
@enable_mode |
| 183 |
def restore(self, filename=None, path=""): |
| 184 |
if not filename: |
| 185 |
raise ValueError("'file_name' value is required for restore") |
| 186 |
cmd = f"configure replace {path}{filename} force" |
| 187 |
return self.send_command(cmd) |
| 188 |
|
| 189 |
def get_diff( |
| 190 |
self, |
| 191 |
candidate=None, |
| 192 |
running=None, |
| 193 |
diff_match="line", |
| 194 |
diff_ignore_lines=None, |
| 195 |
path=None, |
| 196 |
diff_replace="line", |
| 197 |
): |
| 198 |
""" |
| 199 |
Generate diff between candidate and running configuration. If the |
| 200 |
remote host supports onbox diff capabilities ie. supports_onbox_diff in that case |
| 201 |
candidate and running configurations are not required to be passed as argument. |
| 202 |
In case if onbox diff capability is not supported candidate argument is mandatory |
| 203 |
and running argument is optional. |
| 204 |
:param candidate: The configuration which is expected to be present on remote host. |
| 205 |
:param running: The base configuration which is used to generate diff. |
| 206 |
:param diff_match: Instructs how to match the candidate configuration with current device configuration |
| 207 |
Valid values are 'line', 'strict', 'exact', 'none'. |
| 208 |
'line' - commands are matched line by line |
| 209 |
'strict' - command lines are matched with respect to position |
| 210 |
'exact' - command lines must be an equal match |
| 211 |
'none' - will not compare the candidate configuration with the running configuration |
| 212 |
:param diff_ignore_lines: Use this argument to specify one or more lines that should be |
| 213 |
ignored during the diff. This is used for lines in the configuration |
| 214 |
that are automatically updated by the system. This argument takes |
| 215 |
a list of regular expressions or exact line matches. |
| 216 |
:param path: The ordered set of parents that uniquely identify the section or hierarchy |
| 217 |
the commands should be checked against. If the parents argument |
| 218 |
is omitted, the commands are checked against the set of top |
| 219 |
level or global commands. |
| 220 |
:param diff_replace: Instructs on the way to perform the configuration on the device. |
| 221 |
If the replace argument is set to I(line) then the modified lines are |
| 222 |
pushed to the device in configuration mode. If the replace argument is |
| 223 |
set to I(block) then the entire command block is pushed to the device in |
| 224 |
configuration mode if any line is not correct. |
| 225 |
:return: Configuration diff in json format. |
| 226 |
{ |
| 227 |
'config_diff': '', |
| 228 |
'banner_diff': {} |
| 229 |
} |
| 230 |
""" |
| 231 |
diff = {} |
| 232 |
device_operations = self.get_device_operations() |
| 233 |
option_values = self.get_option_values() |
| 234 |
|
| 235 |
if candidate is None and device_operations["supports_generate_diff"]: |
| 236 |
raise ValueError("candidate configuration is required to generate diff") |
| 237 |
|
| 238 |
if diff_match not in option_values["diff_match"]: |
| 239 |
raise ValueError( |
| 240 |
"'match' value %s in invalid, valid values are %s" |
| 241 |
% (diff_match, ", ".join(option_values["diff_match"])), |
| 242 |
) |
| 243 |
|
| 244 |
if diff_replace not in option_values["diff_replace"]: |
| 245 |
raise ValueError( |
| 246 |
"'replace' value %s in invalid, valid values are %s" |
| 247 |
% (diff_replace, ", ".join(option_values["diff_replace"])), |
| 248 |
) |
| 249 |
|
| 250 |
# prepare candidate configuration |
| 251 |
candidate_obj = NetworkConfig(indent=1) |
| 252 |
want_src, want_banners = self._extract_banners(candidate) |
| 253 |
candidate_obj.load(want_src) |
| 254 |
|
| 255 |
if running and diff_match != "none": |
| 256 |
# running configuration |
| 257 |
have_src, have_banners = self._extract_banners(running) |
| 258 |
running_obj = NetworkConfig(indent=1, contents=have_src, ignore_lines=diff_ignore_lines) |
| 259 |
configdiffobjs = candidate_obj.difference( |
| 260 |
running_obj, |
| 261 |
path=path, |
| 262 |
match=diff_match, |
| 263 |
replace=diff_replace, |
| 264 |
) |
| 265 |
|
| 266 |
else: |
| 267 |
configdiffobjs = candidate_obj.items |
| 268 |
have_banners = {} |
| 269 |
|
| 270 |
diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else "" |
| 271 |
banners = self._diff_banners(want_banners, have_banners) |
| 272 |
diff["banner_diff"] = banners if banners else {} |
| 273 |
return diff |
| 274 |
|
| 275 |
@enable_mode |
| 276 |
def configure(self): |
| 277 |
""" |
| 278 |
Enter global configuration mode based on the |
| 279 |
status of commit_confirm |
| 280 |
:return: None |
| 281 |
""" |
| 282 |
if self.get_option("commit_confirm_timeout") or self.get_option("commit_confirm_immediate"): |
| 283 |
commit_timeout = ( |
| 284 |
self.get_option("commit_confirm_timeout") |
| 285 |
if self.get_option("commit_confirm_timeout") |
| 286 |
else 1 |
| 287 |
) # add default timeout not default: 1 to support above or operation |
| 288 |
|
| 289 |
persistent_command_timeout = self._connection.get_option("persistent_command_timeout") |
| 290 |
# check archive state |
| 291 |
archive_state = self.send_command("show archive") |
| 292 |
rollback_state = self.send_command("show archive config rollback timer") |
| 293 |
|
| 294 |
if persistent_command_timeout > commit_timeout * 60: |
| 295 |
raise ValueError( |
| 296 |
"ansible_command_timeout can't be greater than commit_confirm_timeout " |
| 297 |
"Please adjust and try again", |
| 298 |
) |
| 299 |
|
| 300 |
if re.search(r"Archive.*not.enabled", archive_state): |
| 301 |
raise ValueError( |
| 302 |
"commit_confirm_immediate option set, but archiving " |
| 303 |
"not enabled on device. " |
| 304 |
"Please set up archiving and try again", |
| 305 |
) |
| 306 |
|
| 307 |
if not re.search(r"%No Rollback Confirmed Change pending", rollback_state): |
| 308 |
raise ValueError( |
| 309 |
"Existing rollback change already pending. " |
| 310 |
"Please resolve by issuing 'configure confirm' " |
| 311 |
"or 'configure revert now'", |
| 312 |
) |
| 313 |
|
| 314 |
self.send_command(f"configure terminal revert timer {commit_timeout}") |
| 315 |
else: |
| 316 |
self.send_command("configure terminal") |
| 317 |
|
| 318 |
@enable_mode |
| 319 |
def edit_config(self, candidate=None, commit=True, replace=None, comment=None): |
| 320 |
resp = {} |
| 321 |
operations = self.get_device_operations() |
| 322 |
self.check_edit_config_capability(operations, candidate, commit, replace, comment) |
| 323 |
|
| 324 |
results = [] |
| 325 |
requests = [] |
| 326 |
# commit confirm specific attributes |
| 327 |
commit_confirm = self.get_option("commit_confirm_immediate") |
| 328 |
if commit: |
| 329 |
self.configure() |
| 330 |
for line in to_list(candidate): |
| 331 |
if not isinstance(line, Mapping): |
| 332 |
line = {"command": line} |
| 333 |
|
| 334 |
cmd = line["command"] |
| 335 |
if cmd != "end" and cmd[0] != "!": |
| 336 |
results.append(self.send_command(**line)) |
| 337 |
requests.append(cmd) |
| 338 |
|
| 339 |
self.send_command("end") |
| 340 |
if commit_confirm: |
| 341 |
self.send_command("configure confirm") |
| 342 |
|
| 343 |
else: |
| 344 |
raise ValueError("check mode is not supported") |
| 345 |
|
| 346 |
resp["request"] = requests |
| 347 |
resp["response"] = results |
| 348 |
return resp |
| 349 |
|
| 350 |
@enable_mode |
| 351 |
def edit_config_with_prompt(self, candidate=None, commit=True, replace=None, comment=None): |
| 352 |
resp = {} |
| 353 |
operations = self.get_device_operations() |
| 354 |
self.check_edit_config_capability(operations, candidate, commit, replace, comment) |
| 355 |
|
| 356 |
results = [] |
| 357 |
requests = [] |
| 358 |
# commit confirm specific attributes |
| 359 |
commit_confirm = self.get_option("commit_confirm_immediate") |
| 360 |
if commit: |
| 361 |
self.configure() |
| 362 |
for item_dict in candidate: |
| 363 |
config_line = item_dict.get("config_line") |
| 364 |
prompt = item_dict.get("prompt") |
| 365 |
answer = item_dict.get("answer") |
| 366 |
|
| 367 |
if config_line != "end" and config_line[0] != "!": |
| 368 |
results.append( |
| 369 |
self.send_command(command=config_line, prompt=prompt, answer=answer), |
| 370 |
) |
| 371 |
requests.append(config_line) |
| 372 |
|
| 373 |
self.send_command("end") |
| 374 |
if commit_confirm: |
| 375 |
self.send_command("configure confirm") |
| 376 |
|
| 377 |
else: |
| 378 |
raise ValueError("check mode is not supported") |
| 379 |
|
| 380 |
resp["request"] = requests |
| 381 |
resp["response"] = results |
| 382 |
return resp |
| 383 |
|
| 384 |
def edit_macro(self, candidate=None, commit=True, replace=None, comment=None): |
| 385 |
""" |
| 386 |
ios_config: |
| 387 |
lines: "{{ macro_lines }}" |
| 388 |
parents: "macro name {{ macro_name }}" |
| 389 |
after: '@' |
| 390 |
match: line |
| 391 |
replace: block |
| 392 |
""" |
| 393 |
resp = {} |
| 394 |
operations = self.get_device_operations() |
| 395 |
self.check_edit_config_capability(operations, candidate, commit, replace, comment) |
| 396 |
|
| 397 |
results = [] |
| 398 |
requests = [] |
| 399 |
if commit: |
| 400 |
commands = "" |
| 401 |
self.send_command("config terminal") |
| 402 |
time.sleep(0.1) |
| 403 |
# first item: macro command |
| 404 |
commands += candidate.pop(0) + "\n" |
| 405 |
multiline_delimiter = candidate.pop(-1) |
| 406 |
for line in candidate: |
| 407 |
commands += " " + line + "\n" |
| 408 |
commands += multiline_delimiter + "\n" |
| 409 |
obj = {"command": commands, "sendonly": True} |
| 410 |
results.append(self.send_command(**obj)) |
| 411 |
requests.append(commands) |
| 412 |
|
| 413 |
time.sleep(0.1) |
| 414 |
self.send_command("end", sendonly=True) |
| 415 |
time.sleep(0.1) |
| 416 |
results.append(self.send_command("\n")) |
| 417 |
requests.append("\n") |
| 418 |
|
| 419 |
resp["request"] = requests |
| 420 |
resp["response"] = results |
| 421 |
return resp |
| 422 |
|
| 423 |
def get( |
| 424 |
self, |
| 425 |
command=None, |
| 426 |
prompt=None, |
| 427 |
answer=None, |
| 428 |
sendonly=False, |
| 429 |
newline=True, |
| 430 |
output=None, |
| 431 |
check_all=False, |
| 432 |
): |
| 433 |
if not command: |
| 434 |
raise ValueError("must provide value of command to execute") |
| 435 |
if output: |
| 436 |
raise ValueError("'output' value %s is not supported for get" % output) |
| 437 |
|
| 438 |
return self.send_command( |
| 439 |
command=command, |
| 440 |
prompt=prompt, |
| 441 |
answer=answer, |
| 442 |
sendonly=sendonly, |
| 443 |
newline=newline, |
| 444 |
check_all=check_all, |
| 445 |
) |
| 446 |
|
| 447 |
def check_device_type(self): |
| 448 |
device_type = "L2" |
| 449 |
try: |
| 450 |
self.get(command="show vlan") |
| 451 |
except Exception: |
| 452 |
device_type = "L3" |
| 453 |
return device_type |
| 454 |
|
| 455 |
def get_device_info(self): |
| 456 |
if not self._device_info: |
| 457 |
device_info = {} |
| 458 |
|
| 459 |
device_info["network_os"] = "ios" |
| 460 |
# Ensure we are not in config mode |
| 461 |
self._update_cli_prompt_context(config_context=")#", exit_command="end") |
| 462 |
reply = self.get(command="show version") |
| 463 |
data = to_text(reply, errors="surrogate_or_strict").strip() |
| 464 |
match = re.search(r"Version (\S+)", data) |
| 465 |
if match: |
| 466 |
device_info["network_os_version"] = match.group(1).strip(",") |
| 467 |
|
| 468 |
model_search_strs = [ |
| 469 |
r"^[Cc]isco (.+) \(revision", |
| 470 |
r"^[Cc]isco (\S+).+bytes of .*memory", |
| 471 |
] |
| 472 |
for item in model_search_strs: |
| 473 |
match = re.search(item, data, re.M) |
| 474 |
if match: |
| 475 |
version = match.group(1).split(" ") |
| 476 |
device_info["network_os_model"] = version[0] |
| 477 |
break |
| 478 |
|
| 479 |
match = re.search(r"^(.+) uptime", data, re.M) |
| 480 |
if match: |
| 481 |
device_info["network_os_hostname"] = match.group(1) |
| 482 |
|
| 483 |
match = re.search(r'image file is "(.+)"', data) |
| 484 |
if match: |
| 485 |
device_info["network_os_image"] = match.group(1) |
| 486 |
device_info["network_os_type"] = self.check_device_type() |
| 487 |
self._device_info = device_info |
| 488 |
|
| 489 |
return self._device_info |
| 490 |
|
| 491 |
def get_device_operations(self): |
| 492 |
return { |
| 493 |
"supports_diff_replace": True, |
| 494 |
"supports_commit": False, |
| 495 |
"supports_rollback": False, |
| 496 |
"supports_defaults": True, |
| 497 |
"supports_onbox_diff": False, |
| 498 |
"supports_commit_comment": False, |
| 499 |
"supports_multiline_delimiter": True, |
| 500 |
"supports_diff_match": True, |
| 501 |
"supports_diff_ignore_lines": True, |
| 502 |
"supports_generate_diff": True, |
| 503 |
"supports_replace": False, |
| 504 |
} |
| 505 |
|
| 506 |
def get_option_values(self): |
| 507 |
return { |
| 508 |
"format": ["text"], |
| 509 |
"diff_match": ["line", "strict", "exact", "none"], |
| 510 |
"diff_replace": ["line", "block"], |
| 511 |
"output": [], |
| 512 |
} |
| 513 |
|
| 514 |
def get_capabilities(self): |
| 515 |
result = super(Cliconf, self).get_capabilities() |
| 516 |
result["rpc"] += ["edit_banner", "get_diff", "run_commands", "get_defaults_flag"] |
| 517 |
result["device_operations"] = self.get_device_operations() |
| 518 |
result.update(self.get_option_values()) |
| 519 |
return json.dumps(result) |
| 520 |
|
| 521 |
def edit_banner(self, candidate=None, multiline_delimiter="@", commit=True): |
| 522 |
""" |
| 523 |
Edit banner on remote device |
| 524 |
:param banners: Banners to be loaded in json format |
| 525 |
:param multiline_delimiter: Line delimiter for banner |
| 526 |
:param commit: Boolean value that indicates if the device candidate |
| 527 |
configuration should be pushed in the running configuration or discarded. |
| 528 |
:param diff: Boolean flag to indicate if configuration that is applied on remote host should |
| 529 |
generated and returned in response or not |
| 530 |
:return: Returns response of executing the configuration command received |
| 531 |
from remote host |
| 532 |
""" |
| 533 |
resp = {} |
| 534 |
banners_obj = json.loads(candidate) |
| 535 |
results = [] |
| 536 |
requests = [] |
| 537 |
if commit: |
| 538 |
for key, value in banners_obj.items(): |
| 539 |
key += " %s" % multiline_delimiter |
| 540 |
self.send_command("config terminal", sendonly=True) |
| 541 |
for cmd in [key, value, multiline_delimiter]: |
| 542 |
obj = {"command": cmd, "sendonly": True} |
| 543 |
results.append(self.send_command(**obj)) |
| 544 |
requests.append(cmd) |
| 545 |
|
| 546 |
self.send_command("end", sendonly=True) |
| 547 |
time.sleep(0.1) |
| 548 |
results.append(self.send_command("\n")) |
| 549 |
requests.append("\n") |
| 550 |
|
| 551 |
resp["request"] = requests |
| 552 |
resp["response"] = results |
| 553 |
|
| 554 |
return resp |
| 555 |
|
| 556 |
def run_commands(self, commands=None, check_rc=True): |
| 557 |
if commands is None: |
| 558 |
raise ValueError("'commands' value is required") |
| 559 |
|
| 560 |
responses = list() |
| 561 |
for cmd in to_list(commands): |
| 562 |
if not isinstance(cmd, Mapping): |
| 563 |
cmd = {"command": cmd} |
| 564 |
|
| 565 |
output = cmd.pop("output", None) |
| 566 |
if output: |
| 567 |
raise ValueError("'output' value %s is not supported for run_commands" % output) |
| 568 |
|
| 569 |
try: |
| 570 |
out = self.send_command(**cmd) |
| 571 |
except AnsibleConnectionFailure as e: |
| 572 |
if check_rc: |
| 573 |
raise |
| 574 |
out = getattr(e, "err", to_text(e)) |
| 575 |
|
| 576 |
responses.append(out) |
| 577 |
|
| 578 |
return responses |
| 579 |
|
| 580 |
def get_defaults_flag(self): |
| 581 |
""" |
| 582 |
The method identifies the filter that should be used to fetch running-configuration |
| 583 |
with defaults. |
| 584 |
:return: valid default filter |
| 585 |
""" |
| 586 |
out = self.get("show running-config ?") |
| 587 |
out = to_text(out, errors="surrogate_then_replace") |
| 588 |
|
| 589 |
commands = set() |
| 590 |
for line in out.splitlines(): |
| 591 |
if line.strip(): |
| 592 |
commands.add(line.strip().split()[0]) |
| 593 |
|
| 594 |
if "all" in commands: |
| 595 |
return "all" |
| 596 |
else: |
| 597 |
return "full" |
| 598 |
|
| 599 |
def set_cli_prompt_context(self): |
| 600 |
""" |
| 601 |
Make sure we are in the operational cli mode |
| 602 |
:return: None |
| 603 |
""" |
| 604 |
if self._connection.connected: |
| 605 |
out = self._connection.get_prompt() |
| 606 |
|
| 607 |
if out is None: |
| 608 |
raise AnsibleConnectionFailure( |
| 609 |
message="cli prompt is not identified from the last received" |
| 610 |
" response window: %s" % self._connection._last_recv_window, |
| 611 |
) |
| 612 |
|
| 613 |
if re.search(r"config.*\)#", to_text(out, errors="surrogate_then_replace").strip()): |
| 614 |
self._connection.queue_message("vvvv", "wrong context, sending end to device") |
| 615 |
self._connection.send_command("end") |
| 616 |
|
| 617 |
def _extract_banners(self, config): |
| 618 |
banners = {} |
| 619 |
banner_cmds = re.findall(r"^banner (\w+)", config, re.M) |
| 620 |
for cmd in banner_cmds: |
| 621 |
regex = r"banner %s \^C(.+?)(?=\^C)" % cmd |
| 622 |
match = re.search(regex, config, re.S) |
| 623 |
if match: |
| 624 |
key = "banner %s" % cmd |
| 625 |
banners[key] = match.group(1).strip() |
| 626 |
|
| 627 |
for cmd in banner_cmds: |
| 628 |
regex = r"banner %s \^C(.+?)(?=\^C)" % cmd |
| 629 |
match = re.search(regex, config, re.S) |
| 630 |
if match: |
| 631 |
config = config.replace(str(match.group(1)), "") |
| 632 |
|
| 633 |
config = re.sub(r"banner \w+ \^C\^C", "!! banner removed", config) |
| 634 |
return config, banners |
| 635 |
|
| 636 |
def _diff_banners(self, want, have): |
| 637 |
candidate = {} |
| 638 |
for key, value in want.items(): |
| 639 |
if value != have.get(key): |
| 640 |
candidate[key] = value |
| 641 |
return candidate |