def __init__(self): self.restart_proceed = Statement(pattern=pat.restart_proceed, action='sendline(y)', loop_continue=True, continue_timer=False) self.factory_reset = Statement(pattern=pat.factory_reset, action='sendline(Y)', loop_continue=True, continue_timer=False) self.press_any_key = Statement(pattern=pat.press_any_key, action=None, args=None, loop_continue=False, continue_timer=False) self.login = Statement(pattern=pat.login, action=None, args=None, loop_continue=False, continue_timer=False) self.connection_closed = Statement(pattern=pat.connection_closed, action=update_context, args={'console': False}, loop_continue=False, continue_timer=False)
def __init__(self): ''' All CIMC Statements ''' super().__init__() self.paginate_stmt = \ Statement(pattern=p.paging_options, action=paginate, args=None, loop_continue=True, continue_timer=True) self.press_enter_space_q_stmt = \ Statement(pattern=p.press_enter_space_q, action=press_space, args=None, loop_continue=True, continue_timer=True) self.continue_stmt = \ Statement(pattern=p.continue_prompt, action='sendline(y)', args=None, loop_continue=True, continue_timer=True)
def config_transition(statemachine, spawn, context): # Config may be locked, retry until max attempts or config state reached wait_time = spawn.settings.CONFIG_LOCK_RETRY_SLEEP max_attempts = spawn.settings.CONFIG_LOCK_RETRIES dialog = Dialog([Statement(pattern=statemachine.get_state('enable').pattern, loop_continue=False, trim_buffer=True), Statement(pattern=statemachine.get_state('config').pattern, loop_continue=False, trim_buffer=False), ]) if hasattr(statemachine, 'config_transition_statement_list'): dialog += Dialog(statemachine.config_transition_statement_list) for attempt in range(max_attempts + 1): spawn.sendline(statemachine.config_command) dialog.process(spawn, timeout=spawn.settings.CONFIG_TIMEOUT, context=context) statemachine.detect_state(spawn) if statemachine.current_state == 'config': return if attempt < max_attempts: spawn.log.warning('*** Could not enter config mode, waiting {} seconds. Retry attempt {}/{} ***'.format( wait_time, attempt + 1, max_attempts)) sleep(wait_time) raise StateMachineError('Unable to transition to config mode')
def __init__(self): # Rommon > self.add_statement(Statement(pattern=r'^(.*)(rommon(.*))+>.*$', action=print_message, args={'message': 'Device reached rommon prompt in break boot stage', 'status': 0}, loop_continue=False, continue_timer=False)) # Login prompt self.add_statement(Statement(pattern=r'^.*(Username|login): ?$', action=print_message, args={'message': 'Device reached login prompt before rommon prompt', 'status': 0}, loop_continue=False, continue_timer=False)) # Exec Prompt (ex: 'Router>') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^>])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?>$', action='sendline(en)', loop_continue=True, continue_timer=False)) # Privileged Exec Prompt (ex: 'Router#') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^#])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?#$', action=print_message, args={'message': 'Device has reached privileged exec prompt', 'status': 1}, loop_continue=False, continue_timer=False))
def __init__(self, patterns): self.login_password_statement = Statement(pattern=patterns.prompt.password_prompt, action=password_handler, args={'password': patterns.login_password}, loop_continue=True, continue_timer=True) self.sudo_password_statement = Statement(pattern=patterns.prompt.password_prompt, action=password_handler, args={'password': patterns.sudo_password}, loop_continue=True, continue_timer=True) self.expert_to_enable_statement = Statement(pattern=patterns.prompt.password_prompt, action=password_handler, args={'password': patterns.sudo_password}, loop_continue=True, continue_timer=True) self.enable_password_statement = Statement(pattern=patterns.prompt.disable_prompt, action=enable_handler, args={'password': patterns.enable_password}, loop_continue=True, continue_timer=True) self.enable_no_password_statement = Statement(pattern=patterns.prompt.disable_prompt, action=enable_handler, args={'password': ''}, loop_continue=True, continue_timer=True)
def call_service(self, file_path=None, overwrite=True): file_path = Statement(pattern=patterns.file_save, action=sendPath, args={'path': file_path}, loop_continue=True, continue_timer=False) self.dialog.append(file_path) if (overwrite is False): self.error_pattern += [r'^.*exists, overwrite\? \[Y/N\]:'] save_overwrite = Statement(pattern=patterns.overwrite, action=send_response, args={'response': 'N'}, loop_continue=True, continue_timer=False) self.dialog.append(save_overwrite) else: self.error_pattern = [] save_overwrite = Statement(pattern=patterns.overwrite, action=send_response, args={'response': 'Y'}, loop_continue=True, continue_timer=False) self.dialog.append(save_overwrite) super().call_service("save")
def configure_enable_aes_encryption(device, master_key): """ enables aes password encryption Args: device ('obj'): Device object master_key ('str'): Master key(New key with minimum length of 8 chars) Returns: None Raises: SubCommandError """ dialog = Dialog( [ Statement( pattern=r".*New\s*key.*", action=f"sendline({master_key})", loop_continue=True, continue_timer=False, ), Statement( pattern=r".*Confirm\s*key.*", action=f"sendline({master_key})", loop_continue=True, continue_timer=False, ) ] ) try: device.configure("key config-key password-encrypt", reply=dialog) device.configure("password encryption aes") except SubCommandFailure as e: raise SubCommandFailure( "Could not enables aes password encryption on device {device}.\nError:" " {e}".format(device=device.name, e=str(e)) )
def module_to_fxos_transition(statemachine, spawn, context): if context.get('_mod_con_type') == 'telnet': spawn.sendline('exit') dialog = Dialog([ Statement(pattern=patterns.no_such_command, action='send(~)', args=None, loop_continue=True), Statement(pattern=patterns.telnet_escape_prompt, action='sendline(q)', args=None, loop_continue=False), ]) statemachine.go_to('any', spawn, timeout=spawn.timeout, dialog=dialog) spawn.sendline() else: try: spawn.send( '~\x17' ) # ~ should be sufficient, but tests show ctrl-w is needed spawn.expect(patterns.telnet_escape_prompt, timeout=10, log_timeout=False) spawn.sendline('q') except UniconTimeoutError: spawn.sendline('\x17') # Ctrl-W to clear the line chatty_term_wait(spawn) spawn.sendline('exit')
def __init__(self): super().__init__() self.login_stmt = Statement(pattern=patterns.username_prompt, action=xr_login_handler, args=None, loop_continue=True, continue_timer=False) self.bmc_login_stmt = Statement(pattern=patterns.bmc_login_prompt, action=bmc_login_handler, args=None, loop_continue=True, continue_timer=False) self.password_stmt = Statement(pattern=patterns.password_prompt, action=password_handler, args=None, loop_continue=True, continue_timer=False) self.secret_password_stmt = Statement( pattern=patterns.secret_password_prompt, action=password_handler, args={'reuse_current_credential': True}, loop_continue=True, continue_timer=False)
def _reloadLc(self, lc): """Do the reload LC action for asr1k devices. Args: Mandatory: lc (`str`) : LC slot number need to reload. Raises: Unicon errors Example: >>> _reloadLc(lc='27') """ # unicon dialog = Dialog([ Statement(pattern=r'Proceed\[y\/n\]\?.*', action='sendline(y)', loop_continue=True, continue_timer=False), Statement(pattern=r'\(y\/n\)\?.*', action='sendline(y)', loop_continue=True, continue_timer=False) ]) # Execute command to reload LC self.device.execute('reload module {}'.format(lc), reply=dialog) time.sleep(5)
def __init__(self): self.add_statement(Statement(pattern=r'(.*)(loader(.*))+>', action=print_message, args={'message':"Device reached loader prompt"}, loop_continue=False, continue_timer=False, trim_buffer=False)) self.add_statement(Statement(pattern=r'^.*(Username|login): ?$', action=print_message, args={'message': "Device reached login before loader prompt", 'raise_exception': True}, loop_continue=False, continue_timer=False)) self.add_statement(Statement(pattern=r'^[^\n]*#\s?$', action=print_message, args={'message': "Device reached enable mode before loader prompt", 'raise_exception': True}, loop_continue=False, continue_timer=False)) self.add_statement(Statement(pattern=r'Abort( Power On)? Auto Provisioning .*:', action='sendline(yes)', args=None, loop_continue=True, continue_timer=False))
def __init__(self): ''' All junos Statements ''' self.bad_password_stmt = Statement(pattern=pat.bad_passwords, action=bad_password_handler, args=None, loop_continue=False, continue_timer=False) self.login_incorrect = Statement(pattern=pat.login_incorrect, action=incorrect_login_handler, args=None, loop_continue=True, continue_timer=False) self.login_stmt = Statement(pattern=pat.username, action=login_handler, args=None, loop_continue=True, continue_timer=False) self.useraccess_stmt = Statement(pattern=pat.useracess, action=user_access_verification, args=None, loop_continue=True, continue_timer=False) self.password_stmt = Statement(pattern=pat.password, action=password_handler, args=None, loop_continue=True, continue_timer=False)
def __init__(self): # Login prompt self.add_statement(Statement(pattern=r'^.*(Username|login): ?$', action=print_message, args={'message': 'Device reached login prompt before rommon prompt', 'raise_exception': True})) # Would you like to enter the initial configuration dialog? [yes/no]: self.add_statement(Statement(pattern=r'^.*(initial|basic) configuration dialog *\?.*', action='sendline(no)', loop_continue=True)) # Would you like to terminate autoinstall? self.add_statement(Statement(pattern=r'^.*terminate autoinstall *\?.*', action='sendline(yes)', loop_continue=True)) # Exec Prompt (ex: 'Router>') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^>])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?>$', action='sendline(en)', loop_continue=True)) # Privileged Exec Prompt (ex: 'Router#') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^#])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?#$', action=print_message, args={'message': 'Device has reached privileged exec prompt'}))
def __init__(self): # Rommon > self.add_statement(Statement(pattern=r'^(.*)((rommon(.*))+>|switch *:).*$', action=print_message, args={'message': 'Device reached rommon prompt in break boot stage'}, trim_buffer=False)) # grub> self.add_statement(Statement(pattern=r'.*grub *>.*', action=print_message, args={'message': 'Device reached grub prompt in break boot stage'}, trim_buffer=False)) # Login prompt self.add_statement(Statement(pattern=r'^.*(Username|login): ?$', action=print_message, args={'message': 'Device reached login prompt before rommon prompt', 'raise_exception': True})) # Exec Prompt (ex: 'Router>') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^>])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?>$', action='sendline(en)', loop_continue=True)) # Privileged Exec Prompt (ex: 'Router#') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^#])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?#$', action=print_message, args={'message': 'Device has reached privileged exec prompt'}))
def install_image(self, steps, device, images, save_system_config=SAVE_SYSTEM_CONFIG, install_timeout=INSTALL_TIMEOUT): with steps.start(f"Installing image '{images[0]}'") as step: install_add_one_shot_dialog = Dialog([ Statement(pattern=r".*Press Quit\(q\) to exit, you may save " r"configuration and re-enter the command\. " r"\[y\/n\/q\]", action='sendline(y)' if save_system_config else 'sendline(n)', loop_continue=True, continue_timer=False), Statement(pattern=r".*Please confirm you have changed boot config " r"to \S+ \[y\/n\]", action='sendline(y)', loop_continue=True, continue_timer=False), Statement(pattern=r".*reload of the system\. " r"Do you want to proceed\? \[y\/n\]", action='sendline(y)', loop_continue=True, continue_timer=False), ]) try: device.reload('install add file {} activate commit'.format(images[0]), reply=install_add_one_shot_dialog, timeout=install_timeout) except Exception as e: step.failed("Failed to install the iamge", from_exception=e) image_mapping = self.history['InstallImage'].parameters.setdefault( 'image_mapping', {}) image_mapping.update({images[0]: self.new_boot_var})
def execute_copy_run_to_start(device, command_timeout=300, max_time=120, check_interval=30, copy_vdc_all=False): ''' Execute copy running-config to startup-config Args: device ('obj'): Device object command_timeout ('int'): Timeout value in sec, Default Value is 300 sec max_time ('int'): Maximum time in seconds, Default Value is 300 sec check_interval ('int'): Check interval in seconds, Default Value is 20 sec copy_vdc_all ('boolean'): Copy on all VDCs or not, Default Value is False ''' # Build command cmd = "copy running-config startup-config" if copy_vdc_all: cmd += " vdc-all" # Build Unicon Dialogs startup = Statement( pattern=r'^.*Destination +(filename|file +name)(\s\(control\-c +to +abort\)\:)? +\[(\/)?startup\-config]\?', action='sendline()', loop_continue=True, continue_timer=False) proceed = Statement( pattern=r'.*proceed anyway?.*', action='sendline(y)', loop_continue=True, continue_timer=False) # XR platform specific when over-write the existing configurations yes_cmd = Statement( pattern=r'^.*The +destination +file +already +exists\. +Do +you +want +to +overwrite\? +\[no\]\:', action='sendline(y)', loop_continue=True, continue_timer=False) # Begin timeout timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: output = device.execute(cmd, timeout=command_timeout, reply=Dialog([startup, proceed, yes_cmd])) except Exception as e: raise Exception("Cannot save running-config to startup-config {}".\ format(str(e))) # IOSXE platform if "[OK]" in output or "Copy complete" in output: break # Copy in progress... if "system not ready" in output or "Building configuration..." in output: log.info("Still building configuration. Re-attempting save config " "after '{}' seconds".format(check_interval)) timeout.sleep() continue else: # No break raise Exception('Failed to save running-config to startup-config')
def install_packages(section, steps, device, packages, save_system_config=False, install_timeout=300): """ Clean yaml file schema: ----------------------- install_packages: packages: <Packages to install `list`> (Mandatory) save_system_config: <Whether or not to save the system config if it was modified `bool`> (Optional) Default: False install_timeout: <Maximum time to wait for install process to finish `int`> (Optional) Default: 300 Example: -------- install_image: images: - /auto/some-location/that-this/image/stay-isr-image.bin save_system_config: True install_timeout: 1000 """ install_add_one_shot_dialog = Dialog([ Statement( pattern=r".*Press Quit\(q\) to exit, you may save " r"configuration and re-enter the command\. " r"\[y\/n\/q\]", action='sendline(y)' if save_system_config else 'sendline(n)', loop_continue=True, continue_timer=False), Statement(pattern=r".*Please confirm you have changed boot config " r"to \S+ \[y\/n\]", action='sendline(y)', loop_continue=True, continue_timer=False), Statement(pattern=r".*This operation may require a reload of the " r"system\. Do you want to proceed\? \[y\/n\]", action='sendline(y)', loop_continue=True, continue_timer=False), ]) for pkg in packages: with steps.start("Installing package '{pkg}' onto {dev}".format( pkg=pkg, dev=device.hostname)) as step: try: device.execute( 'install add file {} activate commit'.format(pkg), reply=install_add_one_shot_dialog, error_pattern=['.*FAILED: install_add_activate_commit.*'], timeout=install_timeout) except Exception as e: step.failed( "Installing package '{pkg}' failed. Error: {e}".format( pkg=pkg, e=str(e)))
def __init__(self): # Login prompt self.add_statement(Statement(pattern=r'^.*(Username|login)\:.*$', #^.*(Username|login): ?$', action=print_message, args={'message': 'Successfully recovered Active RP'}, loop_continue=False, continue_timer=False)) # Would you like to enter the initial configuration dialog? [yes/no]: self.add_statement(Statement(pattern=r'^.*(initial|basic) configuration dialog *\?.*', action='sendline(no)', loop_continue=True, continue_timer=False)) # Would you like to terminate autoinstall? self.add_statement(Statement(pattern=r'^.*terminate autoinstall *\?.*', action='sendline(yes)', loop_continue=True, continue_timer=False)) # Press RETURN to get started self.add_statement(Statement(pattern=r'^.*Press RETURN to get started.*', action='sendline()', loop_continue=True, continue_timer=False)) # Exec Prompt (ex: 'Router>') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^>])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?>$', action='sendline(en)', loop_continue=True, continue_timer=False)) # Privileged Exec Prompt (ex: 'Router#') self.add_statement(Statement(pattern=r'^(Router|Switch|ios|switch|.+[^#])(\\(standby\\))?(\\(-stby)\\)?(\\(boot\\))?#$', action=None, args=None, loop_continue=False, continue_timer=False)) # Standby prompt (ex: 'This (D)RP Node is not ready or active for login /configuration') self.add_statement(Statement(pattern=r'^.*This \(D\)RP +Node +is +not +ready +or +active +for +login \/configuration', action=print_message, args={'message': 'Successfully recovered Standby RP'}, loop_continue=False, continue_timer=False)) # Privileged Exec Prompt (ex: 'RP/0/RSP0/CPU0#') self.add_statement(Statement(pattern=r'^RP\/0\/RSP(0|1)\/CPU0\:.*#$', action='sendline()', args=None, loop_continue=False, continue_timer=False)) # Privileged Exec Prompt (ex: 'PE1 con0/RSP0/CPU0 is in standby') self.add_statement(Statement(pattern=r'^.*(\S+)?.*con(0|1)\/RSP(0|1)\/CPU0 +is(( +in +standby)|( +now +available))', action='sendline()', args=None, loop_continue=False, continue_timer=False))
def __init__(self): ''' All FTD Statements ''' self.cssp_stmt = Statement(patterns.cssp_pattern, action=flag_ssh_session, args=None, loop_continue=True, continue_timer=False) self.bell_stmt = Statement(patterns.bell_pattern, action=clear_command_line, args=None, loop_continue=True, continue_timer=False) self.command_not_completed_stmt = Statement(patterns.command_not_completed, action=clear_command_line, args=None, loop_continue=True, continue_timer=False) self.config_call_home_stmt = Statement(patterns.config_call_home_prompt, action='sendline(n)', args=None, loop_continue=True, continue_timer=False) self.ftd_reboot_confirm_stmt = Statement(patterns.ftd_reboot_confirm, action='sendline(yes)', args=None, loop_continue=True, continue_timer=False) self.fxos_mgmt_reboot_stmt = Statement(patterns.fxos_mgmt_reboot_confirm, action='sendline(yes)', args=None, loop_continue=True, continue_timer=False) self.enable_username_stmt = Statement(patterns.username, action=enable_username_handler, args=None, loop_continue=True, continue_timer=False) self.enable_password_stmt = Statement(patterns.password, action=enable_password_handler, args=None, loop_continue=True, continue_timer=False) self.boot_interrupt_stmt = Statement(patterns.boot_interrupt, action='send(\x1b)', args=None, loop_continue=True, continue_timer=False)
class WebserverStatements: login_password_statement = Statement( pattern=WebserverPatterns.password_prompt, action=password_handler, args={'password': WebserverConstants.login_password}, loop_continue=True, continue_timer=True) sudo_password_statement = Statement( pattern=WebserverPatterns.password_prompt, action=password_handler, args={'password': WebserverConstants.sudo_password}, loop_continue=True, continue_timer=True)
def restore_configuration(self, device, method, abstract): if method == 'checkpoint': # Enable the feature dialog = Dialog([ Statement(pattern=r'\[no\]', action='sendline(y)', loop_continue=True, continue_timer=False) ]) cfg = 'load disk0:{name} commit replace'.format(name=self.ckname) device.configure(cfg, reply=dialog) # need to delete the config file on the device dialog = Dialog([ Statement(pattern=r'\[confirm\]', action='sendline(y)', loop_continue=True, continue_timer=False) ]) device.execute('delete disk0:{name}'.format(name=self.ckname), reply=dialog) # Keeping them for later enhancement elif method == 'local': pass elif method == 'config_replace': # Build command cmd = "load {}\n"\ "commit replace".format(self.to_url) # Execute the following commands: # PE1# load location:<filename> # PE1# commit replace device.configure(cmd) # Delete location:<filename> self.filetransfer.deletefile(target=self.to_url, device=device) # Verify location:<filename> deleted dir_output = self.filetransfer.dir(target=self.to_url, device=device) for file in dir_output: if self.filename in file: break else: log.info("Successfully deleted '{}'".format(self.to_url)) return raise Exception("Unable to delete '{}'".format(self.to_url)) else: pass
def __init__(self, patterns): self.login_password = Statement( pattern=patterns.prompt.prelogin_prompt, action=login_handler, args={'patterns': patterns}, loop_continue=False, continue_timer=True) self.login_incorrect = Statement( pattern='Login incorrect', action=login_with_factory_default_password, args={'patterns': patterns}, loop_continue=False, continue_timer=False)
def config_transition(statemachine, spawn, context): # Config may be locked, retry until max attempts or config state reached wait_time = spawn.settings.CONFIG_LOCK_RETRY_SLEEP max_attempts = spawn.settings.CONFIG_LOCK_RETRIES dialog = Dialog([ Statement(pattern=patterns.config_locked, action=update_context, args={'config_locked': True}, loop_continue=False, trim_buffer=True), Statement(pattern=statemachine.get_state('enable').pattern, action=update_context, args={'config_locked': False}, loop_continue=False, trim_buffer=False), Statement(pattern=statemachine.get_state('config').pattern, action=update_context, args={'config_locked': False}, loop_continue=False, trim_buffer=False) ]) for attempts in range(max_attempts + 1): spawn.sendline(statemachine.config_command) try: dialog.process(spawn, timeout=spawn.settings.CONFIG_TIMEOUT, context=context) except UniconTimeoutError: pass if context.get('config_locked'): if attempts < max_attempts: spawn.log.warning( '*** Config lock detected, waiting {} seconds. Retry attempt {}/{} ***' .format(wait_time, attempts + 1, max_attempts)) sleep(wait_time) else: statemachine.detect_state(spawn) if statemachine.current_state == 'config': return else: spawn.log.warning( "Could not enter config mode, sending clear line command and trying again.." ) spawn.send(spawn.settings.CLEAR_LINE_CMD) if context.get('config_locked'): raise StateMachineError('Config locked, unable to configure device') else: raise StateMachineError('Unable to transition to config mode')
def __init__(self, patterns): self.patterns = patterns self.login_password = Statement( pattern=self.patterns.prompt.prelogin_prompt, action=self.login_handler, args=None, loop_continue=True, continue_timer=True) self.login_password_statement = Statement( pattern=patterns.prompt.password_prompt, action=password_handler, args={'password': patterns.login_password}, loop_continue=True, continue_timer=True)
def save_device_information(device): """Save running-configuration to startup-config. This is for general IOSXE devices. Args: Mandatory: device (`obj`) : Device object. Raises: None Example: >>> save_device_information(device=Device()) """ # configure config-register device.configure('config-register 0x2102') # save all configuration to startup for all slots dialog = Dialog([ Statement(pattern=r'Destination +filename +\[.*\].*', action='sendline()', loop_continue=True, continue_timer=False) ]) device.execute('copy running-config nvram:startup-config', reply=dialog) device.execute('write memory')
def enter_shell(device, timeout=60): """Enter shell prompt on IOSXE deivces by using command "request platform software system shell switch active R0" Args: Mandatory: device (`obj`) : Device object. Optional: timeout (`int`) : Command execution timeout. Returns: None Raises: None Example: >>> enter_shell(device=Device()) """ # Run workon.sh on the RP shell dialog = Dialog([ Statement(pattern=r'continue\? +\[y\/n\]', action='sendline(y)', loop_continue=True, continue_timer=False) ]) # store original pattern enable_state = device.state_machine.get_state('enable') device.origin_pattern = enable_state._pattern # Completely remove the enable state pattern and update it with new pattern. enable_state._pattern = [r'(.*)\:\/]\$'] # enter shell device.execute('request platform software system shell switch active R0', reply=dialog)
def copy_file_to_running_config(device, path, file): """ Restore config from local file using copy function Args: device (`obj`): Device object path (`str`): directory file (`str`): file name Returns: None """ dialog = Dialog([ Statement( pattern=r".*Destination filename.*", action="sendline()", loop_continue=True, continue_timer=False, ) ]) try: device.execute( "copy {path}{file} running-config".format(path=path, file=file), reply=dialog, ) except SubCommandFailure as e: raise SubCommandFailure("Could not copy saved configuration on " "device {device}".format(device=device.name))
def execute_write_erase(device, timeout=300): ''' Execute write erase on the device Args: device ('obj'): Device object ''' log.info("Executing Write Erase") write_erase = Statement( pattern=r'.*Do you wish to proceed anyway\? \(y\/n\)\s*\[n\]', action='sendline(y)', loop_continue=True, continue_timer=False) # Add permisson denied to error pattern origin = list(device.execute.error_pattern) error_pattern = ['.*[Pp]ermission denied.*'] error_pattern.extend(origin) try: device.execute("write erase", reply=Dialog([write_erase]), timeout=timeout, error_pattern=error_pattern) except Exception as err: log.error("Failed to write erase: {err}".format(err=err)) raise Exception(err) finally: # restore original error pattern device.execute.error_pattern = origin
def restore_running_config(device, path, file, timeout=60): """ Restore config from local file Args: device (`obj`): Device object path (`str`): directory file (`str`): file name timeout (`int`): Timeout for applying config Returns: None """ dialog = Dialog([ Statement( pattern=r".*Enter Y.*", action="sendline(y)", loop_continue=True, continue_timer=False, ) ]) try: device.execute("configure replace {path}{file}".format(path=path, file=file), reply=dialog, timeout=timeout) except SubCommandFailure as e: raise SubCommandFailure("Could not replace saved configuration on " "device {device}\nError: {e}".format( device=device.name, e=str(e)))
def install_remove_inactive(section, steps, device, timeout=180): """ This stage removes partially installed packages/images left on the device. If a super package is left partially installed, we cannot attempt to install another until it is removed. Stage Schema ------------ install_image: timeout (int, optional): Maximum time to wait for remove process to finish. Defaults to 180. Example ------- install_remove_inactive: timeout: 180 """ with steps.start("Removing inactive packages") as step: install_remove_inactive_dialog = Dialog([ Statement( pattern=r".*Do you want to remove the above files\? \[y\/n\]", action='sendline(y)', loop_continue=False, continue_timer=False), ]) try: device.execute('install remove inactive', reply=install_remove_inactive_dialog, timeout=timeout) except Exception as e: step.failed( "Remove inactive packages failed. Error: {e}".format(e=str(e)))