def run_test(provider): root = provider.get_session().get_root_schema() service = gNMIService() """Create interface configuration""" ifc = ifmgr.InterfaceConfigurations.InterfaceConfiguration() ifc.active = 'act' ifc.interface_name = 'Loopback10' ifc.description = 'Test interface' ifc.interface_virtual = Empty() ip_address = ifmgr.InterfaceConfigurations.InterfaceConfiguration.Ipv4Network.Addresses.Primary( ) ip_address.address = '172.16.255.1' ip_address.netmask = '255.255.255.255' ifc.ipv4_network.addresses.primary = ip_address ifc_create = ifmgr.InterfaceConfigurations() ifc_create.interface_configuration.append(ifc) ifc_create.yfilter = YFilter.update reply = service.set(provider, ifc_create) """Read interface configuration""" ifc_filter = ifmgr.InterfaceConfigurations() ifc = ifmgr.InterfaceConfigurations.InterfaceConfiguration() ifc.active = '"act"' ifc.interface_name = '"Loopback10"' ifc_filter.interface_configuration.append(ifc) ifc_read = service.get(provider, ifc_filter) if ifc_read is not None: print_entity(ifc_read, root) """Need to fix bug in the XR bundle: missing directory _yang in distribution: RuntimeError: YIllegalStateError: Could not create repository in: /usr/local/lib/python2.7/dist-packages/ydk/models/cisco_ios_xr/_yang from ydk.services import CodecService from ydk.providers import CodecServiceProvider codec_service = CodecService() codec_provider = CodecServiceProvider(type='json') payload = codec_service.encode(codec_provider, ifc_read) print('CREATED INTERFACE CONFIGURATION:') print(payload) """ """Delete interface configuration""" ifc_delete = ifmgr.InterfaceConfigurations() ifc = ifmgr.InterfaceConfigurations.InterfaceConfiguration() ifc.active = '"act"' ifc.interface_name = '"Loopback10"' ifc_delete.interface_configuration.append(ifc) ifc_delete.yfilter = YFilter.delete reply = service.set(provider, ifc_delete)
def create_loopback(self, arg_loopbacknum, arg_ip, arg_mask): interface_configurations = Cisco_IOS_XR_ifmgr_cfg.InterfaceConfigurations() interface_configuration = interface_configurations.InterfaceConfiguration() interface_configuration.active = "act" interface_configuration.interface_name = "Loopback" + arg_loopbacknum interface_configuration.interface_virtual = ydk.types.Empty() #interface_configuration.description = "CONNECTS TO LSR1 (g0/0/0/1)" #mtu = interface_configuration.mtus.Mtu() #mtu.owner = "GigabitEthernet" #mtu.mtu = 9192 #interface_configuration.mtus.mtu.append(mtu) #interface_configuration.statistics.load_interval = 30 # regular_address = addresses.regular_addresses.RegularAddress() primary_address = interface_configuration.ipv4_network.addresses.Primary() primary_address.address = arg_ip primary_address.netmask = arg_mask interface_configuration.ipv4_network.addresses.primary = primary_address interface_configurations.interface_configuration.append(interface_configuration) self.xr.ydk_crud.create(self.xr.ydk_provider, interface_configurations)
def print_interfaces(self): filter = Cisco_IOS_XR_ifmgr_cfg.InterfaceConfigurations() interfaces = self.xr.ydk_crud.read(self.xr.ydk_provider, filter) for intf in interfaces.interface_configuration: print(intf.interface_name)
def prepare_config(): ''' use YDK object and populate the data engine takes care of XML encoding ''' interface_configurations = ifmgr_model.InterfaceConfigurations() interface = interface_configurations.InterfaceConfiguration() interface_configurations.interface_configuration.append(interface) interface.active = "act" interface.interface_name = "Loopback0" interface.description = "Demo interface config via YDK ifmgr_model" interface.interface_virtual = ytypes.Empty() primary = interface.ipv4_network.addresses.Primary() interface.ipv4_network.addresses.primary = primary primary.address = "172.16.255.1" primary.netmask = "255.255.255.255" return interface_configurations
def run_test(provider): root = provider.get_session().get_root_schema() crud = CRUDService() """Create interface configuration""" ifc = ifmgr.InterfaceConfigurations.InterfaceConfiguration() ifc.active = 'act' ifc.interface_name = 'Loopback10' ifc.description = 'Test interface' ifc.interface_virtual = Empty() ip_address = ifmgr.InterfaceConfigurations.InterfaceConfiguration.Ipv4Network.Addresses.Primary( ) ip_address.address = '172.16.255.1' ip_address.netmask = '255.255.255.255' ifc.ipv4_network.addresses.primary = ip_address ifc_create = ifmgr.InterfaceConfigurations() ifc_create.interface_configuration.append(ifc) reply = crud.update(provider, ifc_create) """Read interface operational data""" ifc_oper_filter = ifoper.InterfaceProperties() dn = ifoper.InterfaceProperties.DataNodes.DataNode() dn.data_node_name = '"0/RP0/CPU0"' ifc_oper_filter.data_nodes.data_node.append(dn) lview = ifoper.InterfaceProperties.DataNodes.DataNode.Locationviews.Locationview( ) lview.locationview_name = '"0/RP0/CPU0"' dn.locationviews.locationview.append(lview) ifc = ifoper.InterfaceProperties.DataNodes.DataNode.Locationviews.Locationview.Interfaces.Interface( ) ifc.interface_name = '"Loopback10"' ifc.state = YFilter.read lview.interfaces.interface.append(ifc) ifc_oper_data = crud.read(provider, ifc_oper_filter) if ifc_oper_data is not None: print('INTERFACE OPERATIONAL DATA:') print_entity(ifc_oper_data, root)
def deleteVlanFromExisitingInterface(device,interface,vlan): """ Deletes subinterface on a Cisco ASR9XXX. TODO: Add multi device and multi vendor support Consider adding IPv6 support in the future When vendor has the OC model working implement it. Author: David J. Stern Date: DEC 2017 Parameters: device: (str): device type [UNUSED for future use] interface: (str): Vendor identifier of interface/subinterface vlan: (int): vlan number to use [will be casted to int if you send str] Returns: (boolean): True for success of the deletion. On Error: (Any Exception to call): Returns False """ interface_configurations2 = xr_ifmgr_cfg.InterfaceConfigurations().InterfaceConfiguration() interface_configurations2.interface_name = str(interface)+"."+str(vlan) interface_configurations2.interface_mode_non_physical = xr_ifmgr_cfg.InterfaceModeEnumEnum.default interface_configurations2.active = "act" provider = NetconfServiceProvider(address=currentEdgeDeviceInfo['IPv4'],port=,username=currentEdgeDeviceInfo['username'],password=currentEdgeDeviceInfo['password'],protocol="ssh") crud = CRUDService() try: crud.delete(provider, interface_configurations2) except: provider.close() return (False) provider.close() return(True)
def create_loopback(self, arg_loopbacknum, arg_ip, arg_mask): interface_configurations = Cisco_IOS_XR_ifmgr_cfg.InterfaceConfigurations( ) interface_configuration = interface_configurations.InterfaceConfiguration( ) interface_configuration.active = "act" interface_configuration.interface_name = "Loopback" + arg_loopbacknum interface_configuration.interface_virtual = ydk.types.Empty() primary_address = interface_configuration.ipv4_network.addresses.Primary( ) primary_address.address = arg_ip primary_address.netmask = arg_mask interface_configuration.ipv4_network.addresses.primary = primary_address interface_configurations.interface_configuration.append( interface_configuration) self.xr.ydk_crud.create(self.xr.ydk_provider, interface_configurations)
help="print debugging messages", action="store_true") args = parser.parse_args() # log debug messages if verbose argument specified if args.verbose: logger = logging.getLogger("ydk") logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter(("%(asctime)s - %(name)s - " "%(levelname)s - %(message)s")) handler.setFormatter(formatter) logger.addHandler(handler) # create codec provider provider = CodecServiceProvider(type="xml") # create codec service codec = CodecService() interface_configurations = xr_ifmgr_cfg.InterfaceConfigurations( ) # create object config_interface_configurations( interface_configurations) # add object configuration # encode and print object print(codec.encode(provider, interface_configurations)) exit() # End of script
http://ydk.cisco.com/py/docs/gen_doc_df76b47e76a58aa15aee29b3b0484ba370fd9172.html """ from ydk.types import Empty from ydk.services import CRUDService from ydk.providers import NetconfServiceProvider from ydk.models.cisco_ios_xr import Cisco_IOS_XR_ifmgr_cfg provider = NetconfServiceProvider(address='xrv', port=830, username="******", password="******", protocol="ssh") crud = CRUDService() ifcfg = Cisco_IOS_XR_ifmgr_cfg.InterfaceConfigurations() # This instantiates a list of interface configuration objects. interface_config = ifcfg.InterfaceConfiguration() # This instantiates an interface configuration object interface_config.active = 'act' interface_config.interface_name = 'Loopback100' interface_config.interface_virtual = Empty() # This object needs to be present to trigger creation of the virtual interface, but in itself it has no value. primary_ip = interface_config.ipv4_network.addresses.Primary() # This instantiates a primary IP address object. This is done because Primary is a presence class. # As a result it will be assigned the 'None' value when instantiated normally. Therefore we must specifically # create a primary IP address instance and then attach it to the configuration. primary_ip.address = '100.100.1.1' primary_ip.netmask = '255.255.255.0'
def create_service(request, nc_provider): # create CRUD service crud = CRUDService() # create codec provider codec_provider = CodecServiceProvider(type="xml") # create codec service codec = CodecService() interface_name = request['interface-name'] # create ifmgr obj if_cfg = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration() if_cfg.active = "act" if_cfg.interface_name = interface_name if_cfg.interface_mode_non_physical = xr_ifmgr_cfg.InterfaceModeEnum.l2_transport # creat ethernet service Encapsulation obj if_cfg.ethernet_service.encapsulation = if_cfg.ethernet_service.Encapsulation( ) encap_type = xr_eth_infra_dt.Match.match_dot1q encap_value = xr_eth_infra_dt.Vlan = int(request['vlan-id']) if_cfg.ethernet_service.encapsulation.outer_tag_type = encap_type if_cfg.ethernet_service.encapsulation.outer_range1_low = encap_value if_cfg.ethernet_service.rewrite = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration.EthernetService.Rewrite( ) rewrite_type = xr_eth_infra_dt.Rewrite.pop1 if_cfg.ethernet_service.rewrite.rewrite_type = rewrite_type # create localtraffic obj local_traffic_def_encap = if_cfg.ethernet_service.LocalTrafficDefaultEncapsulation( ) if_cfg.ethernet_service.local_traffic_default_encapsulation = local_traffic_def_encap if_cfg.ethernet_service.local_traffic_default_encapsulation = if_cfg.ethernet_service.encapsulation # create the interface configurations add the if_cfg to it if_cfgs = xr_ifmgr_cfg.InterfaceConfigurations() if_cfgs.interface_configuration.append(if_cfg) if request['delete-config'] == 'off': crud.create(nc_provider, if_cfgs) elif request['delete-config'] == 'on': crud.delete(nc_provider, if_cfg) # create the l2vpn object, database and pw classes # set enable as "Empty" type l2vpn_cfg = xr_l2vpn_cfg.L2vpn() l2vpn_cfg.enable = Empty() l2vpn_cfg.database = xr_l2vpn_cfg.L2vpn.Database() l2vpn_cfg.database.pseudowire_classes = l2vpn_cfg.Database.PseudowireClasses( ) test_class = xr_l2vpn_cfg.L2vpn.Database.PseudowireClasses.PseudowireClass( ) test_class.name = "ELINE-PW" test_class.enable = Empty() test_class.mpls_encapsulation = xr_l2vpn_cfg.L2vpn.Database.PseudowireClasses.PseudowireClass( ).MplsEncapsulation() test_class.mpls_encapsulation.enable = Empty() test_class.mpls_encapsulation.control_word = xr_l2vpn_cfg.ControlWord.enable flow_label = xr_l2vpn_cfg.FlowLabelLoadBalance() # flow_label = xr_l2vpn_cfg.L2vpn.Database.PseudowireClasses.PseudowireClass.MplsEncapsulation.LoadBalanceGroup.FlowLabelLoadBalance() test_class.mpls_encapsulation.load_balance_group = xr_l2vpn_cfg.L2vpn.Database.PseudowireClasses.PseudowireClass.MplsEncapsulation.LoadBalanceGroup( ) test_class.mpls_encapsulation.load_balance_group.flow_label_load_balance.flow_label = flow_label.both l2vpn_cfg.database.pseudowire_classes.pseudowire_class.append(test_class) l2vpn_cfg.database.xconnect_groups = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups( ) test_group = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup() test_group.name = "ELINE-SVCS" l2vpn_cfg.database.xconnect_groups.xconnect_group.append(test_group) test_group.p2p_xconnects = l2vpn_cfg.Database.XconnectGroups.XconnectGroup.P2pXconnects( ) test_xconnect = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup.P2pXconnects.P2pXconnect( ) test_xconnect.name = request['vlan-id'] + "-" + request['pw-id'] test_group.p2p_xconnects.p2p_xconnect.append(test_xconnect) test_xconnect.attachment_circuits = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup.P2pXconnects.P2pXconnect.AttachmentCircuits( ) test_ac = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup.P2pXconnects.P2pXconnect.AttachmentCircuits.AttachmentCircuit( ) test_ac.name = request['interface-name'] test_ac.enable = Empty() test_xconnect.attachment_circuits.attachment_circuit.append(test_ac) test_xconnect.pseudowires = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup.P2pXconnects.P2pXconnect.Pseudowires( ) test_pw = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup.P2pXconnects.P2pXconnect.Pseudowires.Pseudowire( ) test_pw.pseudowire_id = int(request['pw-id']) test_neighbor = xr_l2vpn_cfg.L2vpn.Database.XconnectGroups.XconnectGroup.P2pXconnects.P2pXconnect.Pseudowires.Pseudowire.Neighbor( ) test_neighbor.neighbor = request['neighbor-ip'] test_neighbor.class_ = "ELINE-PW" test_pw.neighbor.append(test_neighbor) test_xconnect.pseudowires.pseudowire.append(test_pw) the_xml = codec.encode(codec_provider, l2vpn_cfg) if request['delete-config'] == 'off': crud.create(nc_provider, l2vpn_cfg) elif request['delete-config'] == 'on': xc_group = l2vpn_cfg.database.xconnect_groups.xconnect_group.get( "ELINE-SVCS") xc = xc_group.p2p_xconnects.p2p_xconnect[test_xconnect.name] xc.yfilter = YFilter.delete # xc.attachment_circuits.yfilter = YFilter.delete # xc.pseudowires.yfilter = YFilter.delete crud.update(nc_provider, xc_group) return
def create_l3_service(request, nc_provider): # create CRUD service crud = CRUDService() # create codec provider codec_provider = CodecServiceProvider(type="xml") # create codec service codec = CodecService() # interface configuration interface_name = request['interface-name'] # create ifmgr obj if_cfg = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration() if_cfg.active = "act" if_cfg.interface_name = interface_name if_cfg.interface_mode_non_physical = xr_ifmgr_cfg.InterfaceModeEnum.default if_cfg.statistics = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration.Statistics( ) if_cfg.statistics.load_interval = 30 if_cfg.ipv4_network = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration.Ipv4Network( ) if_cfg.ipv4_network.addresses = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration.Ipv4Network( ).Addresses() primary_address = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration.Ipv4Network( ).Addresses().Primary() primary_address.address = request['intf-ip'] primary_address.netmask = "255.255.255.252" if_cfg.ipv4_network.addresses.primary = primary_address if_cfg.vlan_sub_configuration = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration( ).VlanSubConfiguration() if_cfg.vlan_sub_configuration.vlan_identifier = xr_ifmgr_cfg.InterfaceConfigurations.InterfaceConfiguration( ).VlanSubConfiguration().VlanIdentifier() if_cfg.vlan_sub_configuration.vlan_identifier.first_tag = int( request['vlan-id']) encap_type = xr_eth_infra_dt.Vlan.vlan_type_dot1q if_cfg.vlan_sub_configuration.vlan_identifier.vlan_type = encap_type the_xml = codec.encode(codec_provider, if_cfg) # logging.info(the_xml) # create the interface configurations add the if_cfg to it if_cfgs = xr_ifmgr_cfg.InterfaceConfigurations() if_cfgs.interface_configuration.append(if_cfg) if request['delete-config'] == 'off': crud.create(nc_provider, if_cfgs) elif request['delete-config'] == 'on': crud.delete(nc_provider, if_cfg) # global configuration bgp = xr_ipv4_bgp_cfg.Bgp() instance = bgp.Instance() instance.instance_name = "default" instance_as = instance.InstanceAs() instance_as.as_ = 0 four_byte_as = instance_as.FourByteAs() four_byte_as.as_ = int(request['bgp-as']) four_byte_as.bgp_running = Empty() # global address family global_af = four_byte_as.default_vrf.global_.global_afs.GlobalAf() global_af.af_name = xr_ipv4_bgp_datatypes.BgpAddressFamily.ipv4_unicast global_af.enable = Empty() global_af.sourced_networks = four_byte_as.default_vrf.global_.global_afs.GlobalAf( ).SourcedNetworks() network = four_byte_as.default_vrf.global_.global_afs.GlobalAf( ).SourcedNetworks().SourcedNetwork() addr_parsed = request['intf-ip'].split('.') addr = addr_parsed[0] + "." + addr_parsed[1] + "." + addr_parsed[2] + ".0" network.network_addr = addr network.network_prefix = int(request['mask']) global_af.sourced_networks.sourced_network.append(network) four_byte_as.default_vrf.global_.global_afs.global_af.append(global_af) instance_as.four_byte_as.append(four_byte_as) instance.instance_as.append(instance_as) bgp.instance.append(instance) the_xml = codec.encode(codec_provider, bgp) logging.info(the_xml) if request['delete-config'] == 'off': crud.create(nc_provider, bgp) elif request['delete-config'] == 'on': bgp_instance = bgp.instance['default'] sourced = bgp.instance['default'].instance_as['0'].four_byte_as[ request['bgp-as']].default_vrf.global_.global_afs.global_af[ 'ipv4-unicast'].sourced_networks sn = sourced.sourced_network[addr, int(request['mask'])] sn.yfilter = YFilter.delete crud.update(nc_provider, bgp) return
def addVlanToExisitingInterface(device,interface,vlan): """ Adds a subinterface to a Cisco ASR. Automatically assigns ip addressing based on the VLAN used. TODO: Add multi device and multi vendor support Consider adding IPv6 support in the future Consider impact of autoassignment on multiple interfaces on a single device and potential collisions. Integrate to Defense Digital Storefront to obtain order information to place on interface. When vendor has the OC model working implement it. Author: David J. Stern Date: DEC 2017 Parameters: device: (str): device type [UNUSED for future use] interface: (str): Vendor identifier of interface/subinterface vlan: (int): vlan number to use [will be casted to int if you send str] Returns: (boolean,YDK crud response, dictWanIp Object): (boolean): Success of the creation (YDK crud response): YDK response object (dictWanIp Object): Dict of IP addressing used. On Error: (Any Exception to call): Returns False,{},{}. """ interface_configurations = xr_ifmgr_cfg.InterfaceConfigurations() # configure IPv4 address interface_configuration = interface_configurations.InterfaceConfiguration() interface_configuration.active = "act" interface_configuration.interface_name = str(interface)+"."+str(vlan) interface_configuration.interface_mode_non_physical = xr_ifmgr_cfg.InterfaceModeEnumEnum.default interface_configuration.description = "Connect to AWS CJON No. XXXXXX" primary = interface_configuration.ipv4_network.addresses.Primary() #get ipv4 addressing for wan dictWanIp=getInternetAddressPairForWan(int(vlan)) primary.address = dictWanIp['ipDisaDemarc'] primary.netmask = dictWanIp['ipNetmask'] interface_configuration.ipv4_network.addresses.primary = primary subinterface = interface_configuration.VlanSubConfiguration().VlanIdentifier() subinterface.first_tag=int(vlan) subinterface.vlan_type=VlanEnum(2) interface_configuration.vlan_sub_configuration.vlan_identifier = subinterface interface_configurations.interface_configuration.append(interface_configuration) # create NETCONF provider provider = NetconfServiceProvider(address=currentEdgeDeviceInfo['IPv4'],port=,username=currentEdgeDeviceInfo['username'],password=currentEdgeDeviceInfo['password'],protocol="ssh") # create CRUD service crud = CRUDService() try: response=crud.create(provider, interface_configurations) except: provider.close() return (False,{},{}) provider.close() return (True,response,dictWanIp)
from netconf.models import NetConf from ydk.models.cisco_ios_xr import Cisco_IOS_XR_ifmgr_cfg as ifmgr_cfg from ydk.models.cisco_ios_xr import Cisco_IOS_XR_telemetry_model_driven_cfg as mdt_cfg from ydk.services import CodecService from ydk.providers import CodecServiceProvider json_provider = CodecServiceProvider(type='json') xml_provider = CodecServiceProvider(type='xml') codec = CodecService() if_cfgs = ifmgr_cfg.InterfaceConfigurations() mdt = mdt_cfg.TelemetryModelDriven() xrv = NetConf(address='167.205.3.51', port=22, username='******', password='******') if xrv.session is not None: result = xrv.get(read_filter=mdt) else: result = None if result is not None: print(result) print(type(result)) else: print('Can\'t get any result, maybe its client error.') # sleep(4)
username=device.username, password=device.password, protocol=device.scheme) # Instantiate codec providers with json and xml options json_provider = CodecServiceProvider(type='json') xml_provider = CodecServiceProvider(type='xml') # create CRUD service crud = CRUDService() # create codec service codec = CodecService() # create object interface_configurations = xr_ifmgr_cfg.InterfaceConfigurations() oc_ifaces = openconfig_interfaces.Interfaces() # create NETCONF operation try: _result = crud.read_config(provider, interface_configurations) if _result is not None: result_json = codec.encode(json_provider, _result) with open("rd_ifmgr_cfg.json", "w") as f: f.write(result_json) result_xml = codec.encode(xml_provider, _result) with open("rd_ifmgr_cfg.xml", "w") as f: f.write(result_xml) except YServiceProviderError as err: print("NETCONF FAILED with Error:") print(err.message.split('</error-message>')[0].split('"en">')[1])