def configure_interface_pim(device, interface, pim_mode): """ Configure pim in interface Args: device (`obj`): Device object interface (`str`): Interface to get address pim_mode (`str`): PIM mode (sparse-mode | sparse-dense-mode) Returns: None Raises: SubCommandFailure """ configs = [] configs.append("interface {intf}".format(intf=interface)) configs.append("ip pim {mode}".format(mode=pim_mode)) try: device.configure(configs) except SubCommandFailure as e: raise SubCommandFailure( "Failed to configure PIM mode {mode} on interface " "{interface} on device {dev}. Error:\n{error}".format( mode=pim_mode, interface=interface, dev=device.name, error=e, ))
def clear_dmvpn_statistics(device, interface=None, vrf=None, timeout=30): """ clear_dmvpn_statistics Args: device (`obj`): Device object interface('str', optional): Tunnel interface name, default is None vrf('str', optional) : vrf name, default is None timeout('int', optional): timeout for exec command execution, default is 30 Returns: None Raises: SubCommandFailure """ cmd = "clear dmvpn statistics" if interface is not None: cmd += f" interface Tunnel {interface}" if vrf is not None: cmd += f" vrf {vrf}" try: device.execute(cmd, error_pattern=[f'VRF \"{vrf}\" is not valid.','% Invalid input detected at \'\^\' marker\.'], timeout=timeout) except SubCommandFailure as e: raise SubCommandFailure( "Could not clear dmvpn statistics on {device}. Error:\n{error}" .format(device=device, error=e) )
def remove_interface_negotiation(device, interface): """ Remove negotiation auto on interface Args: device (`obj`): Device object interface (`str`): Interface name Returns: None Raises: SubCommandFailure """ log.info( "Removing negotiation auto on interface {interface}".format( interface=interface ) ) try: device.configure( [ "interface {interface}".format(interface=interface), "no negotiation auto", ] ) except SubCommandFailure as e: raise SubCommandFailure( "Failed to unconfig negotiation auto on interface {interface}. Error:\n{error}".format( interface=interface, error=e ) )
def unconfigure_ip_igmp_snooping_vlan_querier(device, vlan_id, querier_ip): """UnConfigure IGMP snooping vlan querier configuration Example : ip igmp snooping vlan 200 querier address 12.1.1.1 Args: device('obj'): Device object vlan_id('int'): vlan id of the switch querier_ip('str'): querier IP address Returns: None Raises: SubCommandFailure """ try: device.configure( "no ip igmp snooping vlan {} querier address {}".format( vlan_id, querier_ip)) except SubCommandFailure as e: log.error(e) raise SubCommandFailure( "Could not unconfigure ip igmp snooping vlan id querier address")
def call_service(self, reload_command='reset system forced', dialog=Dialog([]), timeout=None, **kwargs): con = self.connection timeout = timeout or self.timeout con.log.debug('+++ reloading %s with reload_command %s and timeout is %s +++' % (self.connection.hostname, reload_command, timeout)) dialog += self.dialog_reload try: con.spawn.sendline(reload_command) self.result = dialog.process(con.spawn, timeout=timeout, prompt_recovery=self.prompt_recovery) con.state_machine.go_to('any', con.spawn, context=self.context, prompt_recovery=self.prompt_recovery, timeout=con.connection_timeout, dialog=con.connection_provider.get_connection_dialog()) con.connection_provider.init_handle() except Exception as err: raise SubCommandFailure('Reload failed %s' % err)
def remove_tacacs_server(device, remove_config=None, keyword='tacacs'): """ Remove tacacs server configuration from device Args: device ('obj') : Device object to modify configuration remove_config ('list') : Configuration to be removed from device keyword ('str') : keyword the configuration should start with Returns: None """ config_list = [] if not remove_config: remove_config = get_running_config_section(device=device, keyword=keyword) for line in remove_config: line = line.strip() if line.startswith(keyword): config_list.append(line) unconfig_list = list(map(lambda conf: "no " + conf, config_list)) try: device.configure(unconfig_list) except SubCommandFailure as e: raise SubCommandFailure( "Failed to remove {config} configuration on device " "{device}".format(device=device.name, config=config_list)) from e
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 unconfigure_fnf_monitor_on_interface(device, interface, monitor_name): """ Unconfig Flow Monitor on Interface Args: device (`obj`): Device object interface (`str`): Interface to be unconfigured monitor_name (`str`): Flow monitor name Return: None Raise: SubCommandFailure: Failed unconfiguring interface with flow monitor """ try: device.configure([ "interface {interface}".format(interface=interface), "no ip flow monitor {monitor_name} input".format( monitor_name=monitor_name) ]) except SubCommandFailure: raise SubCommandFailure( 'Could not unconfigure flow monitor {monitor_name} on' 'interface {interface}'.format(monitor_name=monitor_name, interface=interface))
def unconfig_flow_exporter(device, exporter_name, monitor_name): """ Unconfigures Flow Exporter on Device Args: device (`obj`): Device object exporter_name (`str`): Flow exporter name monitor_name (`str`): Flow monitor name Return: None Raise: SubCommandFailure: Failed configuring interface """ try: device.configure([ "no flow monitor {monitor_name}".format(monitor_name=monitor_name), "no flow monitor {exporter_name}".format( exporter_name=exporter_name), "no flow exporter {exporter_name}".format( exporter_name=exporter_name), "no et-analytics" ]) except SubCommandFailure: raise SubCommandFailure( 'Could not unconfigure flow exporter {exporter_name} and flow monitor {monitor_name}' .format(exporter_name=exporter_name, monitor_name=monitor_name))
def unconfigure_flow_exporter_monitor_record(device, exporter_name, monitor_name, record_name): """ Unconfigures Flow Exporter,Monitor and Record on Device Args: device (`obj`): Device object exporter_name (`str`): Flow exporter name monitor_name (`str`): Flow monitor name record_name (`str`): Flow record name Return: None Raise: SubCommandFailure: Failed unconfiguring Flow Exporter,monitor,record """ try: device.configure([ "no flow monitor {monitor_name}".format(monitor_name=monitor_name), "no flow exporter {exporter_name}".format( exporter_name=exporter_name), "no flow record {record_name}".format(record_name=record_name) ]) except SubCommandFailure: raise SubCommandFailure( 'Could not unconfigure flow exporter {exporter_name} and flow' 'monitor {monitor_name} and flow record {record_name}'.format( exporter_name=exporter_name, monitor_name=monitor_name, record_name=record_name))
def configure_fnf_monitor_on_interface(device, interface, monitor_name, direction): """ Config Fnf Monitor on Interface Args: device (`obj`): Device object interface (`str`): Interface to be configured monitor_name (`str`): Flow monitor name direction ('str'): Direction of monitor (input/output) Return: None Raise: SubCommandFailure: Failed configuring interface with flow monitor """ try: device.configure([ "interface {interface}".format(interface=interface), "ip flow monitor {monitor_name} {direction}".format( monitor_name=monitor_name, direction=direction) ]) except SubCommandFailure: raise SubCommandFailure( 'Could not configure fnf monitor {monitor_name} on' 'interface {interface}'.format(monitor_name=monitor_name, interface=interface))
def configure_fnf_exporter(device, exporter_name, dest_ip, source_int, udp_port, timeout): """ Config Flow Exporter on Device Args: device (`obj`): Device object exporter_name (`str`): Flow exporter name dest_ip (`str`): Destination IP source_int('str'): Interface udp_port (`str`): UDP port timeout ('int'): Timeout Return: None Raise: SubCommandFailure: Failed configuring fnf exporter """ try: device.configure([ "flow exporter {exporter_name}".format( exporter_name=exporter_name), "destination {dest_ip}".format(dest_ip=dest_ip), "source {int}".format(int=source_int), "transport udp {udp_port}".format(udp_port=udp_port), "template data timeout {timeout}".format(timeout=timeout), "option vrf-table timeout {timeout}".format(timeout=timeout), "option sampler-table timeout {timeout}".format(timeout=timeout), ]) except SubCommandFailure: raise SubCommandFailure( 'Could not configure fnf exporter {exporter_name}'.format( exporter_name=exporter_name))
def remove_ospf_passive_interface(device, interface, area): """remove passive interface on junos device Args: device (`obj`): Device object interface (`str`): interface to configure ex.) interface = 'tenGigabitEthernet0/4/0' area (`str`): IP address of area Returns: None Raise: SubCommandFailure """ config = [] config.append( "delete protocols ospf area {} interface " "{} passive\n".format(area, interface) ) try: device.configure("".join(config)) except SubCommandFailure as e: raise SubCommandFailure( "Could not remove passive configuration on {interface}. Error:\n{error}".format( interface=interface, error=e ) )
def configure_pvlan_primary(device, primary_vlan, secondary_vlan=None): """ Configures Primary Private Vlan Args: device ('obj'): device to use primary_vlan ('str'): Primary private vlan secondary_vlan ('str',optional): Secondary isolated/community vlan Returns: None Raises: SubCommandFailure """ config_list = [] # vlan 100 # private-vlan primary config_list.append( "vlan {primary_vlan} \n" "private-vlan primary".format(primary_vlan=primary_vlan)) # private-vlan association 101 if secondary_vlan != None: config_list.append("private-vlan association {secondary_vlan}".format( secondary_vlan=secondary_vlan)) try: device.configure(config_list) except SubCommandFailure: raise SubCommandFailure('Could not configure Primary Pvlan')
def configure_policy_map(device, policy_name, class_map_list ): """ Configures policy_map Args: device ('obj'): device to use policy_name('str) : name of the policy name class_map_list('list'): list of data type hold number class map information [ { class_map_name('str') : name of the class policer_val('int',optional): police rate value, match_mode('list',optional): match mode name for cos, matched_value('list',optional): match mode values for cos traffic_class and dscp, table_map_name('str',optional): to set the table name for policy_map, table_map_mode('str',optional : name of the tablemode } ] example: class_map_list=[{'class_map_name':'test1', 'policer_val':2000000000, 'match_mode':['dscp','cos'] 'matched_value':['cs1','5'] 'table_map_name':'table1' 'table_map_mode':'dscp'}] Returns: None Raises: SubCommandFailure """ log.debug( "Configuring policy_map {policy_name} with {class_map_name} ".format( policy_name=policy_name, class_map_name=class_map_list[0]['class_map_name'], ) ) cmd = [f"policy-map {policy_name}"] for class_map in class_map_list: cmd.append(f"class {class_map['class_map_name']}") if 'policer_val' in class_map: cmd.append(f"police rate {class_map['policer_val']}") if class_map.get('match_mode', None) and class_map.get('matched_value', None): for match_mode, matched_value in zip(class_map['match_mode'], class_map['matched_value']): cmd.append(f"set {match_mode} {matched_value}") if 'table_map_name' in class_map: cmd.append(f"set {class_map['table_map_mode']} {class_map['table_map_mode']} table {class_map['table_map_name']}") try: device.configure(cmd) except SubCommandFailure as e: raise SubCommandFailure( "Could not configure class_map. Error:\n{error}".format( error=e ) )
def config_flow_monitor_on_interface(device, interface, exporter_name): """ Config Flow Monitor on Interface Args: device (`obj`): Device object interface (`str`): Interface to be configured exporter_name (`str`): Flow exporter name Return: None Raise: SubCommandFailure: Failed configuring interface """ try: device.configure([ "interface {interface}".format(interface=interface), "et-analytics enable", "ip flow monitor {exporter_name} input".format( exporter_name=exporter_name), "ip flow monitor {exporter_name} output".format( exporter_name=exporter_name) ]) except SubCommandFailure: raise SubCommandFailure( 'Could not configure flow monitor {exporter_name} on interface {interface}' .format(exporter_name=exporter_name, interface=interface))
def unconfigure_policy_map(device, policy_name): """ Unconfigures policy-map Args: device ('obj'): device to use policy_name ('str'): name of the class Returns: None Raises: SubCommandFailure """ log.debug( "Unconfiguring class_map {policy_name}".format( policy_name=policy_name, ) ) cmd = f"no policy-map {policy_name}" try: device.configure(cmd) except SubCommandFailure as e: raise SubCommandFailure( "Could not configure class_map. Error:\n{error}".format( error=e ) )
def configure_interface_passive(device, process_id, interface): """ Configure Interface passive Args: device ('obj'): Device object process_id ('str'): Router ISIS process ID interface ('str'): Interface to configure Returns: None Raises: SubCommandFailure """ try: device.configure("router isis {process_id}\n" " interface {interface}\n" " passive\n" " !\n".format( process_id=process_id, interface=interface, )) except SubCommandFailure: raise SubCommandFailure( "Could not configure interface passive on {device}".format( device=device.name, ))
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}.\nError: {e}".format( device=device.name, e=str(e)))
def stop_packet_capture(device, capture_name): """Stop the packet capture Args: device (`obj`): Device object capture_name (`str`): Packet capture name Returns: None Raises: pyATS Results """ log.info("Stop the packet capture") try: device.execute( "monitor capture {capture_name} stop".format( capture_name=capture_name ) ) except SubCommandFailure as e: raise SubCommandFailure( "Failed in monitor capture, Error: {}".format(str(e)) ) from e
def unconfigure_ip_igmp_snooping_vlan_query_version(device, vlan_id, version_num): """UnConfigure IGMP snooping vlan querier configuration Example : no ip igmp snooping vlan 200 querier version 3 Args: device('obj'): Device object vlan_id('int'): vlan id of the switch version_num('int'): IP IGMP version number Returns: None Raises: SubCommandFailure """ try: device.configure( "no ip igmp snooping vlan {} querier address {}".format( vlan_id, version_num)) except SubCommandFailure as e: log.error(e) raise SubCommandFailure( "Could not configure ip igmp snooping vlan query version")
def execute_delete_boot_variable(device, boot_images=[], timeout=300): ''' Delete the boot variables Args: device ('obj'): Device object boot_images ('list', optional): List of strings of system images to delete as boot variable.default is an empty list timeout ('int'): Max time to delete boot vars in seconds ''' if not boot_images: log.info("Removing boot variable on {device}".format(device=device)) try: device.configure('no boot system') except SubCommandFailure as e: raise SubCommandFailure( "Could not removing boot variable on {device}. Error:\n{error}" .format(device=device, error=e)) else: for image in boot_images: try: device.configure("no boot system {}".format(image), timeout=timeout) except Exception as e: raise Exception("Failed to delete boot variables on '{}'\n{}".\ format(device.name, str(e))) else: log.info("Deleted '{}' from BOOT variable".format(image))
def configure_l2vpn_vfi_context_vpls(device, vpn_id, pseudowire=None): """ Configures l2vpn vfi context vpls on device Args: device('obj'): device to configure vpn_id('str'): vpn_id to configure pseudowire('str', optional): pseudowire to configure, default value is None Returns: N/A Raises: SubCommandFailure """ log.info( "Configuring l2vpn vfi context vpls on {dev}".format(dev=device.name)) config = ["l2vpn vfi context vpls", "vpn id {vpn}".format(vpn=vpn_id)] if pseudowire: for attr in pseudowire: config.append("member {attr}".format(attr=attr)) try: device.configure(config) except SubCommandFailure as e: raise SubCommandFailure("Configuration failed for l2vpn vfi vpls on " "{dev} with exception: {e}".format( dev=device.name, e=str(e)))
def remove_ntp_server(device, servers): """ Remove all configured server using routes Args: device ('obj'): Device object servers ('list'): List of servers to remove(server) ex.) servers = ['192.168.36.11', '192.168.36.12'] Returns: None Raises: SubCommandFailure """ config = [] for route in servers: config.append("no ntp server {}".format(route)) try: device.configure("\n".join(config)) except SubCommandFailure as e: raise SubCommandFailure( "Failed in removing ntp servers " "on device {device}, " "Error: {e}".format(device=device.name, e=str(e)) ) from e
def config_acl_on_interface(device, interface, acl_name, inbound=True): """ Configures acl on interface Args: device ('obj'): device to use interface ('str'): interface to configure acl_name ('str'): acl to apply """ if inbound: log.info( "Configure inbound {acl} on {intf}".format( acl=acl_name, intf=interface ) ) direction = "in" else: log.info( "Configure outbound {acl} on {intf}".format( acl=acl_name, intf=interface ) ) direction = "out" try: device.configure( "interface {intf}\nip access-group {acl} {direction}".format( intf=interface, acl=acl_name, direction=direction ) ) except SubCommandFailure: raise SubCommandFailure( "Could not configure acl {acl} on interface {interface}".format( acl=acl_name, interface=interface ) )
def configure_routing_static_route(device, route, mask, interface=None, destination_address=None): """ Configure static ip route on device Args: device ('str'): Device str route ('str'): ip address for route mask (str): mask the ip address interface ('str'): interface name to configure destination_address('str'): destination address to configure Returns: None Raises: SubCommandFailure """ try: if interface and destination_address: device.configure("ip route " + route + " " + mask + " " + interface + " " + destination_address) elif interface: device.configure("ip route " + route + " " + mask + " " + interface) elif destination_address: device.configure("ip route " + route + " " + mask + " " + destination_address) log.info("Configuration successful for {route} ".format(route=route)) except SubCommandFailure as e: raise SubCommandFailure( "Configuration failed for {route}.".format(route=route))
def unconfigure_interface_description(device, interface): """unconfigure interface description Args: device (`obj`): Device object interface (`str`): Interface name Returns: None Raises: SubCommandFailure """ try: device.configure( [ "interface {interface}".format(interface=interface), "no description", ] ) except SubCommandFailure as e: raise SubCommandFailure( "Could not remove description from interface " "{interface}. Error:\n{error}".format(interface=interface, error=e) )
def unconfigure_ipv6_mld_snooping_vlan_querier_version(device, vlan_id, version_num): """Unconfigure IPv6 MLD Snooping VLAN Querier version Example : no ipv6 mld snooping vlan 200 querier version 2 Args: device('obj'): Device object vlan_id('int'): VLAN ID of the device version_num('int'): MLD Snooping version of the device Returns: None Raises: SubCommandFailure """ try: device.configure( "no ipv6 mld snooping vlan {} querier version {}".format( vlan_id, version_num)) except SubCommandFailure as e: log.error(e) raise SubCommandFailure( "Could not unconfigure ipv6 mld snooping vlan querier address in the device" )
def shut_interface(device, interface): """ Shut interface Args: device (`obj`): Device object interface (`str`): Interface name Returns: None Raises: SubCommandFailure """ if not device.is_connected(): connect_device(device=device) try: device.configure( ["interface {interface}".format(interface=interface), "shutdown"] ) except SubCommandFailure as e: raise SubCommandFailure( "Could not shut interface {intf} on device {dev}. Error:\n{error}".format( intf=interface, dev=device.name, error=e ) )
def get_issu_space_info_on_disk(device, disk, output=""): """ Get free and total space on disk Args: device ('obj'): Device object disk ('str'): Disk name output ('str'): Output from command 'dir {disk}' Return: list: bytes_total ('int'): Total space on disk in bytes bytes_free ('int'): Free space on disk in bytes Raise: SubCommandFailure: Failed executing dir command """ if not output: try: output = device.execute("dir {disk}:".format(disk=disk)) except SubCommandFailure as e: raise SubCommandFailure( "Unable to execute 'dir {disk}'".format(disk)) m = re.search( "(?P<total>(\d+)) +bytes +total +\((?P<free>(\d+)) " "+bytes +free\)", output, ) bytes_total = int(m.groupdict()["total"]) bytes_free = int(m.groupdict()["free"]) return bytes_total, bytes_free