def translate_src_configuration(schema_path, xpath, src_configuration, device_info): tp_info = tp_list.translate_yang_registry.get(device_info) # get tp_info in tp_list trans_info = locate_translation_point_path(schema_path, tp_info, src_configuration) if trans_info is None: raise Exception("did not find translation script") else: translate_py = trans_info[0] # translation script name binding = trans_info[1] # yang bindings yang_base = trans_info[2] # yang_base # use pyangbind to convert xml_obj to yang_obj dummy_root_node = add_to_dummy_xml(src_configuration) module_yang_obj = pybindIETFXMLDecoder.load_xml(dummy_root_node, parent=binding, yang_base=yang_base) # Use the APP's function to convert from Input Python YANG object to its own type. api_name = "_translate__%s" % (safe_name(module_yang_obj._yang_name)) # print(api_name) # The translate API is part of the Yang module's top level object. translate_api = getattr(translate_py, api_name) translated_obj, target_xpath = translate_api(module_yang_obj, None, xpath) # input_obj, translated_obj, xpath xml = pybindIETFXMLEncoder.serialise(translated_obj) # xml parser = etree.XMLParser(remove_blank_text=True) root = etree.fromstring(xml, parser) # lxml obj return root, target_xpath
def build_three_dns(): dhcpd_module = dhcpd() dhcpd_module.dhcp.dns.append("192.168.8.7") dhcpd_module.dhcp.dns.append("192.168.8.8") dhcpd_module.dhcp.dns.append("192.168.8.9") config_str = ("<config>" + pybindIETFXMLEncoder.serialise(dhcpd_module.dhcp) + "</config>") return config_str
def calculate_diff(left, right, snoObject=sno()): left_dict = json.loads(pybindJSON.dumps(left)) right_dict = json.loads(pybindJSON.dumps(right)) right_side_recursion(left_dict, right_dict) left_after_right_recursion = snoObject pybindJSONDecoder.load_json(left_dict, None, None, left_after_right_recursion) left_xml = (pybindIETFXMLEncoder.serialise(left_after_right_recursion)) right_xml = (pybindIETFXMLEncoder.serialise(right)) root_left = etree.fromstring(left_xml) root_right = etree.fromstring(right_xml) left_side_recursion(root_left, root_right) return (etree.tostring(root_left).decode())
def rpc_get(self, session, rpc, filter_or_none): # pylint: disable=W0613 """ Retrieve all or part of specified configuration. :param session: the server session with the client :type session: NetconfServerSession :param rpc: the topmost element in the received message :type rpc: lxml.Element :param filter_or_none: the filter element if present :type filter_or_none: lxml.Element or None :return: "nc:data" type containing the requested state :rtype: lxml.Element """ logger.debug("GET") try: # extract bn, En and eq from running configuration datastore using pyangbind format eq = str(self.configuration.DRoF_configuration.equalization) bn, En = self.extract_bn_and_En(self.configuration) # DAC/OSC setup result = self.ac.dac_setup(bn, En, eq) # modify SNR and BER in running configuration datastore SNR = result[0] BER = result[1] self.modify_SNR_and_BER(BER, SNR) logger.info(pybindJSON.dumps(self.configuration)) # get new SNR and BER from running configuration datastore data = etree.XML(pybindIETFXMLEncoder.serialise( self.configuration)) monitor = data.findall( ".//xmlns:monitor", namespaces={'xmlns': "urn:blueSPACE-DRoF-configuration"}) ber = data.find( ".//xmlns:BER", namespaces={'xmlns': "urn:blueSPACE-DRoF-configuration"}) # create NETCONF rpc-reply message with the new SNR and BER from running configuration datastore data_reply = util.elm("data") top = util.subelm( data_reply, "{urn:blueSPACE-DRoF-configuration}DRoF-configuration") for value in monitor: m = util.subelm(top, 'monitor') m.append(util.leaf_elm('subcarrier-id', str(value[0].text))) m.append(util.leaf_elm('SNR', str(value[1].text))) top.append(util.leaf_elm('BER', str(ber.text))) return util.filter_results(rpc, data_reply, filter_or_none) except Exception as e: logger.error("GET, error: {}".format(e)) raise e
def _getConfigXML_(self, jsonConfig): if jsonConfig["fpga_sw_data"]["sw_type"] == "trustnodev1": tsnTmp = TNsysrepo() pybindJSONDecoder.load_json(jsonConfig["fpga_config"], None, None, obj=tsnTmp) xmlStr = pybindIETFXMLEncoder.serialise(tsnTmp) logging.info("FPGA CONFIG XML:" + xmlStr) return xmlStr return None
def interface2oc(self, input): # debug # print(input) if_model = openconfig_interfaces() for ifname in input: inet = "" if 'inet' in input[ifname]: inet = input[ifname]['inet'] inet6 = "" if 'inet6' in input[ifname]: inet6 = input[ifname]['inet6'] if_model.interfaces.interface.add( ifname).subinterfaces.subinterface.add( 0).ipv4.addresses.address.add(inet) if_model.interfaces.interface[ifname].subinterfaces.subinterface[ 0].ipv6.addresses.address.add(inet6) return "<config>" + pybindIETFXMLEncoder.serialise( if_model.interfaces) + "</config>"
def rpc_edit_config(self, session, rpc, target, method, newconf): # pylint disable=W0613 """ Create, merge or delete all or part of the specified newconf to the running configuration datastore. :param session: the server session with the client :type session: NetconfServerSession :param rpc: the topmost element in the received message :type rpc: lxml.Element :param target: the target of the config, defaults to "running" :type target: str :param method: "merge" (netconf default), "create" or "delete". :type method: str :param newconf: new configuration :type newconf: lxml.Element :return: "nc:data" type containing the requested configuration :rtype: lxml.Element """ # print(etree.tostring(rpc)) # print(etree.tostring(method)) # print(etree.tostring(newconf)) logger.debug("EDIT CONFIG") try: if 'capability' in newconf[0].tag: # TODO to be implemented pass elif 'configuration' in newconf[0].tag: new_xml = pybindIETFXMLDecoder.decode( etree.tostring(newconf), bindingConfiguration, "blueSPACE-DRoF-configuration") if "create" in method.text: # extract NCF, bn, En and eq from newconf NCF = float( new_xml.DRoF_configuration.nominal_central_frequency) eq = str(new_xml.DRoF_configuration.equalization) bn, En = self.extract_bn_and_En(new_xml) # Laser setup self.ac.laser_setup(NCF, self.ac.power_laser) # DAC/OSC setup result = self.ac.dac_setup(bn, En, eq) # save newconf as running configuration self.configuration = new_xml # add SNR and BER to running configuration datastore SNR = result[0] BER = result[1] for i in range(1, len(SNR) + 1): m = self.configuration.DRoF_configuration.monitor.add( i) if np.math.isnan(SNR[i - 1]): m._set_SNR(np.format_float_positional(1e-9)) else: m._set_SNR(SNR[i - 1]) self.configuration.DRoF_configuration._set_BER(BER) logger.info(pybindJSON.dumps(self.configuration)) logger.debug("NEW CONFIGURATION created") elif "merge" in method.text: # extract bn and En from newconf bn, En = self.extract_bn_and_En(new_xml) # extract eq from running configuration datastore eq = str( self.configuration.DRoF_configuration.equalization) # DAC/OSC setup result = self.ac.dac_setup(bn, En, eq) # modify SNR and BER in running configuration datastore SNR = result[0] BER = result[1] self.modify_SNR_and_BER(BER, SNR) # merge newconf with running configuration datastore for i, x in enumerate(new_xml.DRoF_configuration. constellation.iteritems(), start=1): for j, y in enumerate( self.configuration.DRoF_configuration. constellation.iteritems(), start=1): if i == j: y[1].bitsxsymbol = x[1].bitsxsymbol y[1].powerxsymbol = x[1].powerxsymbol logger.info(pybindJSON.dumps(self.configuration)) logger.debug("NEW CONFIGURATION merged") elif "delete" in method.text: # disable Laser and remove logical associations between DAC and OSC self.ac.disable_laser() self.ac.remove_logical_associations() # remove the running configuration self.configuration = bindingConfiguration.blueSPACE_DRoF_configuration( ) logger.info(pybindJSON.dumps(self.configuration)) logger.debug("CONFIGURATION deleted") return util.filter_results( rpc, etree.XML( pybindIETFXMLEncoder.serialise(self.configuration)), None) except Exception as e: logger.error("EDIT CONFIG method {}, error: {}".format(method, e)) raise e
def rpc_edit_config(self, session, rpc, target, method, new_config): # pylint: disable=W0613 logging.debug("---EDIT CONFIG---") logging.debug(session) # print(etree.tostring(rpc)) # print(etree.tostring(method)) # print(etree.tostring(new_config)) # print("RUNNING MONITORING") # subprocess.call(['python', 'application_changes.py']) if 'topology' in new_config[0].tag: topo_path = ".//xmlns:node" topo_namespace = 'urn:node-topology' data_list = new_config.findall( topo_path, namespaces={'xmlns': topo_namespace}) for data in data_list: found = False # print(etree.tostring(data)) for node_id in data.iter("{" + topo_namespace + "}node-id"): topo_list = self.node_topology.findall( topo_path, namespaces={'xmlns': topo_namespace}) for topo in topo_list: # print(etree.tostring(topo)) for node_id2 in topo.iter("{" + topo_namespace + "}node-id"): logging.debug("COMPARING %s - %s" % (node_id.text, node_id2.text)) if node_id.text == node_id2.text: found = True # aux = copy.deepcopy(topo) # aux node topology logging.debug("MATCH") logging.debug("MERGING " + node_id.text) merge(topo, data) # print_config_changes(self.configuration, aux, data, 'modify') # caller(print_config_changes, args=(self.configuration, aux, data, 'modify')) else: logging.debug("NOT MATCH") if not found: logging.debug("APPENDING " + node_id.text) self.node_topology[0].append(data) # print_config_changes(self.configuration, None, data, 'create') # caller(print_config_changes, args=(self.configuration, None, data, 'create')) # print(etree.tostring(self.configuration, encoding='utf8', xml_declaration=True)) return util.filter_results(rpc, self.node_topology, None) elif 'connectivity' in new_config.tag: module_name = 'node-connectivity' connid = new_config.find(".//xmlns:connectionid", namespaces={ 'xmlns': 'urn:node-connectivity' }).text # get connectionid if method.text == "create": logging.debug("CREATING NEW CONNECTION: " + connid) if len(self.node_connectivity.connection ) == 0: # if self.capability is empty self.node_connectivity = new_config logging.debug(self.node_connectivity) # encode to pyangbind format self.node_connectivity = pybindIETFXMLDecoder.decode( etree.tostring(self.node_connectivity), bindingConnection, module_name) else: if connid not in self.node_connectivity.connection: # connectionid no exists tree_config = etree.XML(etree.tostring(new_config)) # decode from pyangbind format xml = pybindIETFXMLEncoder.serialise( self.node_connectivity) tree_node = etree.XML(xml) tree_node.append( tree_config[0]) # adding new connection # encode to pyangbind format self.node_connectivity = pybindIETFXMLDecoder.decode( etree.tostring(tree_node), bindingConnection, 'node-connectivity') elif method.text == "delete": logging.debug("DELETING CONNECTION: " + connid) if connid in self.node_connectivity.connection: # connectionid exists self.node_connectivity.connection.delete(connid) return util.filter_results( rpc, etree.XML( pybindIETFXMLEncoder.serialise(self.node_connectivity)), None)
from Newbinding import openconfig_interfaces from pyangbind.lib.serialise import pybindIETFXMLEncoder import json #https://github.com/robshakir/pyangbind op_if = openconfig_interfaces() NewInt = op_if.interfaces.interface.add('Ten1/0/1') print(json.dumps(NewInt.get(), indent=2)) NewInt.config.description = 'something cool' print(json.dumps(NewInt.get(), indent=2)) print('<config>' + pybindIETFXMLEncoder.serialise(NewInt) + '</config>')
password=Pass, hostkey_verify=False, ) as m: MyFilter = ''' <filter> <lldp-entries xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-lldp-oper"/> </filter> ''' runningConfig = m.get(filter=MyFilter).data_xml dom = xml.dom.minidom.parseString( runningConfig) #or xml.dom.minidom.parse(c) pretty_xml_as_string = dom.toprettyxml() #print(pretty_xml_as_string) dicLldpInt = xmltodict.parse(pretty_xml_as_string) #print(dicLldpInt['data']['lldp-entries']['lldp-entry']) for i in dicLldpInt['data']['lldp-entries']['lldp-entry']: #print(i) op_if = openconfig_interfaces() NewInt = op_if.interfaces.interface.add(fixName(i['local-interface'])) NewInt.config.description = 'connected to ' + i[ 'device-id'] + ' on Int ' + i['connecting-interface'] config = '<config>' + pybindIETFXMLEncoder.serialise( op_if.interfaces) + '</config>' #print(config) output = m.edit_config(target='running', config=config) print(output)
node_con.connection[connectionid].transceiver = transceiverid return node_con if __name__ == '__main__': session = NetconfSSHSession(host, port, username, password) c = addConnection("5001", "65792", "65536", "1") c2 = addConnection("5002", "65536", "65792", "1") c3 = addConnection("5003", "65536", "65792", "1") c4 = addConnection("5004", "65536", "65792", "1") opC = 'create' opD = 'delete' print("--EDIT CONFIG 1--") config = session.edit_config(method=opC, newconf=pybindIETFXMLEncoder.serialise(c)) xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True) print(xmlstr) print("--EDIT CONFIG 2--") config = session.edit_config(method=opC, newconf=pybindIETFXMLEncoder.serialise(c2)) xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True) print(xmlstr) print("--EDIT CONFIG 3--") config = session.edit_config(method=opC, newconf=pybindIETFXMLEncoder.serialise(c3)) xmlstr = etree.tostring(config, encoding='utf8', xml_declaration=True) print(xmlstr)