Пример #1
0
    def _build_yp_establish_subscription_shell(self, datastore,
                                               datastore_subtree_filter,
                                               datastore_xpath_filter):
        es_nsmap = {'yp': 'urn:ietf:params:xml:ns:yang:ietf-yang-push'}
        root = etree.Element(
            'establish-subscription',
            nsmap=es_nsmap,
            attrib={
                'xmlns':
                'urn:ietf:params:xml:ns:yang:ietf-subscribed-notifications'
            })

        datastore_leaf = util.leaf_elm('yp:datastore', f'ds:{datastore}')
        root.append(datastore_leaf)

        if datastore_subtree_filter:
            selection_filter = util.elm('yp:datastore-subtree-filter')
            if isinstance(datastore_subtree_filter, etree.Element):
                selection_filter.append(datastore_subtree_filter)
            else:
                selection_filter.text = datastore_subtree_filter
        elif datastore_xpath_filter:
            selection_filter = util.leaf_elm('yp:datastore-xpath-filter',
                                             datastore_xpath_filter)
        else:
            raise ValueError("Missing selection filter")

        root.append(selection_filter)

        return root
Пример #2
0
    def rpc_full_itu_scan (self, unused_session, rpc, *params):
        # No input values yet
        try:
            if len(params) > 2:
                raise ncerror.RPCSvrInvalidValue(rpc, message="Too many parameters")
            # XXX Should be able to use "j:high-resolution" but it fails
            hires = self._rpc_param_get_boolean(rpc, "high-resolution", False, params)
            power_only = not self._rpc_param_get_boolean(rpc, "detect-presence", False, params)
            if power_only:
                points = self._run_device_method(rpc, self.device.get_itu_power_scan, hires)
            else:
                points = self._run_device_method(rpc, self.device.get_itu_scan, hires)

            result = ncutil.elm("data")
            for tup in points:
                ptelm = ncutil.subelm(result, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", tup[0]))
                if power_only:
                    ptelm.append(ncutil.leaf_elm("j:power", "{:.2f}".format(tup[1].dBm)))
                else:
                    ptelm.append(ncutil.leaf_elm("j:power", "{:.2f}".format(tup[2].dBm)))
                    ptelm.append(ncutil.leaf_elm("j:channel-presence", tup[1]))
            return result
        except jerror.OCMError as ocmerr:
            logger.error("Got OCM error in full itu scan: %s: %s", str(ocmerr),
                         traceback.format_exc())
        except Exception as err:
            logger.error("Got error in full itu scan: %s: %s", str(err),
                         traceback.format_exc())
            raise
Пример #3
0
    def rpc_get_config(self, session, rpc, source_elm, filter_or_none):  # pylint: disable=W0613
        assert source_elm is not None
        if source_elm.find("nc:running", namespaces=NSMAP) is None:
            # Really this should be a different error its a bad value for source not missing
            raise ncerror.MissingElementProtoError(rpc, ncutil.qname("nc:running"))

        data = ncutil.elm("data")
        cont = ncutil.subelm(data, "interfaces")
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "Ethernet0/0"))
        listval.append(ncutil.leaf_elm("shutdown", "true"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "Ethernet0/1"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "FastEthernet1/0"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "FastEthernet1/1"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        # Missing from operational
        listval.append(ncutil.leaf_elm("name", "GigabitEthernet2/0"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))

        return ncutil.filter_results(rpc, data, filter_or_none)
Пример #4
0
def main():
    parser = Parser(__file__)
    args = parser.parse_args()

    session = NetconfSSHSession(args.host, args.port, args.user, args.password)

    es_nsmap = {'yp': 'urn:ietf:params:xml:ns:yang:ietf-yang-push'}
    root = lxml.etree.Element(
        'establish-subscription',
        nsmap=es_nsmap,
        attrib={
            'xmlns':
            'urn:ietf:params:xml:ns:yang:ietf-subscribed-notifications'
        })

    datastore = util.leaf_elm('yp:datastore', 'ds:operational')
    root.append(datastore)

    datastore_xpath_filter = util.leaf_elm('yp:datastore-xpath-filter',
                                           args.xpath)

    root.append(datastore_xpath_filter)

    periodic = util.subelm(root, 'yp:periodic')
    period = util.leaf_elm("yp:period", args.period)
    periodic.append(period)

    res = session.send_rpc(root)

    while True:
        tree, notif, msg = session.get_notification()
        print(etree.tounicode(notif, pretty_print=True), end="\n\n")
Пример #5
0
    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
Пример #6
0
    def _add_config(self, data):
        sysc = util.subelm(data, "sys:system")

        # System Identification
        sysc.append(util.leaf_elm("sys:hostname", socket.gethostname()))

        # System Clock
        clockc = util.subelm(sysc, "sys:clock")
        tzname = time.tzname[time.localtime().tm_isdst]
        clockc.append(
            util.leaf_elm("sys:timezone-utc-offset", int(time.timezone / 100)))
Пример #7
0
    def rpc_get_config(self, session, rpc, source_elm, filter_or_none):  # pylint: disable=W0613
        """Passed the source element"""
        data = util.elm("nc:data")
        sysc = util.subelm(data, "sys:system")
        sysc.append(util.leaf_elm("sys:hostname", socket.gethostname()))

        # Clock
        clockc = util.subelm(sysc, "sys:clock")
        # tzname = time.tzname[time.localtime().tm_isdst]
        clockc.append(util.leaf_elm("sys:timezone-utc-offset", int(time.timezone / 100)))

        return util.filter_results(rpc, data, filter_or_none)
Пример #8
0
    def _send_yp_establish_subscription_periodic(self,
                                                 root,
                                                 period,
                                                 anchor_time=None):
        periodic = util.subelm(root, 'yp:periodic')
        period_leaf = util.leaf_elm("yp:period", period)
        periodic.append(period_leaf)

        if anchor_time:
            anchor_time_leaf = util.leaf_elm("yp:anchor-time", anchor_time)
            periodic.append(anchor_time_leaf)

        return self.send_rpc(root)
Пример #9
0
    def rpc_get(self, unused_session, unused_rpc, filter_elm):
        data = ncutil.elm("data")

        get_data_methods = {
            ncutil.qname("j:ocm-type").text: self.device.get_device_type,
            ncutil.qname("j:oper-mode").text: self.device.get_oper_mode,
            ncutil.qname("j:ident-data").text: self.device.get_idn_string,
            ncutil.qname("j:device-info").text: self.device.get_module_info,
            ncutil.qname("j:application-version").text:
            self.device.get_app_version,
            ncutil.qname("j:temp").text: self.device.get_temp_int,
        }
        if not self.device.get_device_type().startswith("tf"):
            get_data_methods[ncutil.qname(
                "j:safe-version").text] = self.device.get_safe_version

        infonode = ncutil.elm("j:info")
        # infonode = etree.Element(ncutil.qname("j:info"), nsmap={ 'j': NSMAP['j'] })

        # Get filter children
        children = []
        if filter_elm is not None:
            children = filter_elm.getchildren(
            ) if filter_elm is not None else []

        def get_all_values():
            leaf_elms = []
            for key, valuef in get_data_methods.items():
                leaf_elms.append(ncutil.leaf_elm(key, valuef()))
            return leaf_elms

        # No filter children return info only
        if not children:
            ncutil.filter_leaf_values(None, infonode, get_all_values(), data)
            return data

        # Look for info filter.
        finfo = filter_elm.find("info") or filter_elm.find("j:info",
                                                           namespaces=NSMAP)
        if finfo is not None:
            children = finfo.getchildren()
            if not children:
                leaf_elms = get_all_values()
            else:
                leaf_elms = []
                for felm in children:
                    tag = felm.tag
                    if tag in get_data_methods:
                        leaf_elms.append(
                            ncutil.leaf_elm(tag, get_data_methods[tag]()))
                        rv = ncutil.filter_leaf_values(finfo, infonode,
                                                       leaf_elms, data)
                        # Some selector doesn't match return empty.
            if rv is False:
                logger.error("XXX returning False")
                return data

        return data
Пример #10
0
 def rpc_my_cool_rpc(self, session, rpc, *params):
     data = ncutil.elm("nc:data")
     #data = ncutil.elm("data")
     #data.append(ncutil.leaf_elm("pfx:result", "RPC result string"))
     data.append(ncutil.leaf_elm("result", "RPC result string"))
     #print (type(data), data.tag, data.attrib)
     print(etree.tounicode(rpc))
     print(session, params)
     return data
Пример #11
0
    def _rpc_full_scan (self, method, rpc, *params):
        # No input values yet
        if params:
            logging.error("%s: _rpc_full_scan got unexpected params", str(self))
            raise ncerror.RPCSvrErrBadMsg(rpc)

        rv = self._run_device_method(rpc, method)

        result = ncutil.elm("data")
        for port, points in rv:
            portelm = ncutil.elm("j:port")
            result.append(portelm)
            portelm.append(ncutil.leaf_elm("j:port-index", port))
            for freq, power in points:
                ptelm = ncutil.subelm(portelm, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", freq))
                ptelm.append(ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Пример #12
0
    def _rpc_full_scan(self, method, rpc, *params):
        # No input values yet
        if params:
            logging.error("%s: _rpc_full_scan got unexpected params",
                          str(self))
            raise ncerror.RPCSvrErrBadMsg(rpc)

        rv = self._run_device_method(rpc, method)

        result = ncutil.elm("data")
        for port, points in rv:
            portelm = ncutil.elm("j:port")
            result.append(portelm)
            portelm.append(ncutil.leaf_elm("j:port-index", port))
            for freq, power in points:
                ptelm = ncutil.subelm(portelm, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", freq))
                ptelm.append(
                    ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Пример #13
0
    def rpc_frequency_power (self, unused, rpc, *params):
        if len(params) > 1:
            # XXX need a function to look for unknown elements and raise exc for those.
            # XXX really need a better error for not handled params
            raise ncerror.RPCSvrInvalidValue(rpc, message="Too many parameter")

        freq = self._rpc_param_get_frequency(rpc, params)
        power = self._run_device_method(rpc, self.device.get_freq_power, freq)
        result = ncutil.elm("data")
        result.append(ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Пример #14
0
    def rpc_frequency_power(self, unused, rpc, *params):
        if len(params) > 1:
            # XXX need a function to look for unknown elements and raise exc for those.
            # XXX really need a better error for not handled params
            raise ncerror.RPCSvrInvalidValue(rpc, message="Too many parameter")

        freq = self._rpc_param_get_frequency(rpc, params)
        power = self._run_device_method(rpc, self.device.get_freq_power, freq)
        result = ncutil.elm("data")
        result.append(ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Пример #15
0
    def rpc_get_config(self, unused_session, rpc, source_elm,
                       unused_filter_elm):
        assert source_elm is not None
        if source_elm.find("nc:running", namespaces=NSMAP) is None:
            raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm("nc:running"))

        config = ncutil.elm("data")

        if self.is_tfm:
            profile_elm = ncutil.elm("j:scan-profile")
            config.append(profile_elm)
            profile_elm.append(
                ncutil.leaf_elm("j:channel-spacing",
                                self.device.get_channel_spacing()))
            profile_elm.append(
                ncutil.leaf_elm("j:frequency-start",
                                self.device.get_start_freq()))
            profile_elm.append(
                ncutil.leaf_elm("j:frequency-end",
                                self.device.get_stop_freq()))
        else:
            for idx in range(1, 17):
                profile_elm = ncutil.elm("j:channel-profile")
                config.append(profile_elm)
                profile_elm.append(ncutil.leaf_elm("j:profile-index", idx))

                channels = self.device.get_channel_profile(idx)
                for freqs, freqe in channels:
                    channel_elm = ncutil.subelm(profile_elm, "j:channel")
                    range_elm = ncutil.subelm(channel_elm, "j:range")
                    range_elm.append(
                        ncutil.leaf_elm("j:frequency-start", freqs))
                    range_elm.append(ncutil.leaf_elm("j:frequency-end", freqe))
        return config
Пример #16
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        """Passed the filter element or None if not present"""
        data = util.elm("nc:data")

        # if False: # If NMDA
        #     sysc = util.subelm(data, "system")
        #     sysc.append(util.leaf_elm("hostname", socket.gethostname()))

        #     # Clock
        #     clockc = util.subelm(sysc, "clock")
        #     tzname = time.tzname[time.localtime().tm_isdst]
        #     clockc.append(util.leaf_elm("timezone-utc-offset", int(time.timezone / 100)))

        sysc = util.subelm(data, "sys:system-state")
        platc = util.subelm(sysc, "sys:system")

        platc.append(util.leaf_elm("sys:os-name", platform.system()))
        platc.append(util.leaf_elm("sys:os-release", platform.release()))
        platc.append(util.leaf_elm("sys:os-version", platform.version()))
        platc.append(util.leaf_elm("sys:machine", platform.machine()))

        # Clock
        clockc = util.subelm(sysc, "sys:clock")
        now = datetime.datetime.now()
        clockc.append(util.leaf_elm("sys:current-datetime", date_time_string(now)))

        if os.path.exists("/proc/uptime"):
            with open('/proc/uptime', 'r') as f:
                uptime_seconds = float(f.readline().split()[0])
            boottime = time.time() - uptime_seconds
            boottime = datetime.datetime.fromtimestamp(boottime)
            clockc.append(util.leaf_elm("sys:boot-datetime", date_time_string(boottime)))

        return util.filter_results(rpc, data, filter_or_none, self.server.debug)
Пример #17
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        """Passed the filter element or None if not present"""
        data = util.elm("nc:data")

        self._add_config(data)

        #
        # State Data
        #
        sysd = util.subelm(data, "sys:system-state")

        # System Identification
        platc = util.subelm(sysd, "sys:platform")
        platc.append(util.leaf_elm("sys:os-name", platform.system()))
        platc.append(util.leaf_elm("sys:os-release", platform.release()))
        platc.append(util.leaf_elm("sys:os-version", platform.version()))
        platc.append(util.leaf_elm("sys:machine", platform.machine()))

        # System Clock
        clockc = util.subelm(sysd, "sys:clock")
        now = datetime.datetime.now()
        clockc.append(
            util.leaf_elm("sys:current-datetime", date_time_string(now)))

        if os.path.exists("/proc/uptime"):
            with open('/proc/uptime', 'r') as f:
                uptime_seconds = float(f.readline().split()[0])
            boottime = time.time() - uptime_seconds
            boottime = datetime.datetime.fromtimestamp(boottime)
            clockc.append(
                util.leaf_elm("sys:boot-datetime", date_time_string(boottime)))

        return util.filter_results(rpc, data, filter_or_none,
                                   self.server.debug)
Пример #18
0
    def rpc_get_config (self, unused_session, rpc, source_elm, unused_filter_elm):
        assert source_elm is not None
        if source_elm.find("nc:running", namespaces=NSMAP) is None:
            raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm("nc:running"))

        config = ncutil.elm("data")

        if self.is_tfm:
            profile_elm = ncutil.elm("j:scan-profile")
            config.append(profile_elm)
            profile_elm.append(ncutil.leaf_elm("j:channel-spacing",
                                               self.device.get_channel_spacing()))
            profile_elm.append(ncutil.leaf_elm("j:frequency-start",
                                               self.device.get_start_freq()))
            profile_elm.append(ncutil.leaf_elm("j:frequency-end",
                                               self.device.get_stop_freq()))
        else:
            for idx in range(1, 17):
                profile_elm = ncutil.elm("j:channel-profile")
                config.append(profile_elm)
                profile_elm.append(ncutil.leaf_elm("j:profile-index", idx))

                channels = self.device.get_channel_profile(idx)
                for freqs, freqe in channels:
                    channel_elm = ncutil.subelm(profile_elm, "j:channel")
                    range_elm = ncutil.subelm(channel_elm, "j:range")
                    range_elm.append(ncutil.leaf_elm("j:frequency-start", freqs))
                    range_elm.append(ncutil.leaf_elm("j:frequency-end", freqe))
        return config
Пример #19
0
    def rpc_get (self, unused_session, unused_rpc, filter_elm):
        data = ncutil.elm("data")

        get_data_methods = {
            ncutil.qname("j:ocm-type").text: self.device.get_device_type,
            ncutil.qname("j:oper-mode").text: self.device.get_oper_mode,
            ncutil.qname("j:ident-data").text: self.device.get_idn_string,
            ncutil.qname("j:device-info").text: self.device.get_module_info,
            ncutil.qname("j:application-version").text: self.device.get_app_version,
            ncutil.qname("j:temp").text: self.device.get_temp_int,
        }
        if not self.device.get_device_type().startswith("tf"):
            get_data_methods[ncutil.qname("j:safe-version").text] = self.device.get_safe_version

        infonode = ncutil.elm("j:info")
        # infonode = etree.Element(ncutil.qname("j:info"), nsmap={ 'j': NSMAP['j'] })

        # Get filter children
        children = []
        if filter_elm is not None:
            children = filter_elm.getchildren() if filter_elm is not None else []

        def get_all_values ():
            leaf_elms = []
            for key, valuef in get_data_methods.items():
                leaf_elms.append(ncutil.leaf_elm(key, valuef()))
            return leaf_elms

        # No filter children return info only
        if not children:
            ncutil.filter_leaf_values(None, infonode, get_all_values(), data)
            return data

        # Look for info filter.
        finfo = filter_elm.find("info") or filter_elm.find("j:info", namespaces=NSMAP)
        if finfo is not None:
            children = finfo.getchildren()
            if not children:
                leaf_elms = get_all_values()
            else:
                leaf_elms = []
                for felm in children:
                    tag = felm.tag
                    if tag in get_data_methods:
                        leaf_elms.append(ncutil.leaf_elm(tag, get_data_methods[tag]()))
                        rv = ncutil.filter_leaf_values(finfo, infonode, leaf_elms, data)
                        # Some selector doesn't match return empty.
            if rv is False:
                logger.error("XXX returning False")
                return data

        return data
Пример #20
0
    def rpc_full_itu_scan(self, unused_session, rpc, *params):
        # No input values yet
        try:
            if len(params) > 2:
                raise ncerror.RPCSvrInvalidValue(rpc,
                                                 message="Too many parameters")
            # XXX Should be able to use "j:high-resolution" but it fails
            hires = self._rpc_param_get_boolean(rpc, "high-resolution", False,
                                                params)
            power_only = not self._rpc_param_get_boolean(
                rpc, "detect-presence", False, params)
            if power_only:
                points = self._run_device_method(
                    rpc, self.device.get_itu_power_scan, hires)
            else:
                points = self._run_device_method(rpc, self.device.get_itu_scan,
                                                 hires)

            result = ncutil.elm("data")
            for tup in points:
                ptelm = ncutil.subelm(result, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", tup[0]))
                if power_only:
                    ptelm.append(
                        ncutil.leaf_elm("j:power",
                                        "{:.2f}".format(tup[1].dBm)))
                else:
                    ptelm.append(
                        ncutil.leaf_elm("j:power",
                                        "{:.2f}".format(tup[2].dBm)))
                    ptelm.append(ncutil.leaf_elm("j:channel-presence", tup[1]))
            return result
        except jerror.OCMError as ocmerr:
            logger.error("Got OCM error in full itu scan: %s: %s", str(ocmerr),
                         traceback.format_exc())
        except Exception as err:
            logger.error("Got error in full itu scan: %s: %s", str(err),
                         traceback.format_exc())
            raise
Пример #21
0
    def send_hello(self, caplist, session_id=None):
        msg = ncutil.elm("hello", attrib={'xmlns': NSMAP['nc']})
        caps = ncutil.elm("capabilities")
        for cap in caplist:
            ncutil.subelm(caps, "capability").text = str(cap)
        if session_id is not None:
            assert hasattr(self, "methods")
            self.methods.nc_append_capabilities(caps)  # pylint: disable=E1101
        msg.append(caps)

        if self.debug:
            logger.debug("%s: Sending HELLO", str(self))
        if session_id is not None:
            msg.append(ncutil.leaf_elm("session-id", str(session_id)))
        msg = etree.tostring(msg)
        self.send_message(msg.decode('utf-8'))
Пример #22
0
 def send_notification(self, data, *params):
     msg = etree.Element("{{{}}}notification".format(NSMAP['ncEvent']))
     node_event_time = util.leaf_elm(
         'eventTime', date_time_string(datetime.datetime.now()))
     msg.append(node_event_time)
     msg.append(data)
     msg_unicode = etree.tounicode(msg, pretty_print=True)
     logger.debug("notification msg is:\n%s", str(msg_unicode))
     for socket in self.server.sockets:
         if socket.running is False:
             continue
         for session in socket.sessions:
             if session.session_open is False:
                 continue
             logger.debug(
                 "Sending to client, session id: %d, ip:%s, port:%d",
                 session.session_id, socket.client_addr[0],
                 socket.client_addr[1])
             session.send_message(msg_unicode)
     return
Пример #23
0
    def rpc_ownership(self, session, rpc, *params):
        """Passed the filter element or None if not present"""
        data = util.elm("nc:data")
        data.append(util.leaf_elm("result", "RPC result string"))

        xPathResult = rpc.xpath(
            "//nc:ownership/nc:ownerCertificate/nc:certificate",
            namespaces=NSMAP)
        if not xPathResult:
            print("no cert found")
        else:
            certString = xPathResult[0].text
            temp_ownerCert = OpenSSL.crypto.load_certificate(
                OpenSSL.crypto.FILETYPE_PEM, certString)
            #print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT, ownerCert).decode("utf-8"))

        xPathResult = rpc.xpath(
            "//nc:ownership/nc:ownerCertificate/nc:certificateSignature",
            namespaces=NSMAP)

        #if there is no signature at all, just accecpt the unsigned ownerCertificate
        if not xPathResult:
            print("no siganture found")
            self.ownerCertificate = temp_ownerCert

        #if there is a signature, check the signed ownerCertificate and accept it
        else:
            signature_base64 = xPathResult[0].text
            signature = base64.b64decode(signature_base64)
            #print(certString)
            if verifyString(self.manufacturerCert, signature,
                            certString.encode('ascii'), "sha256"):
                self.ownerCertificate = temp_ownerCert
            #print(result)

        #print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT, self.ownerCertificate).decode("utf-8"))
        return util.filter_results(rpc, data, None)
Пример #24
0
 def get_all_values ():
     leaf_elms = []
     for key, valuef in get_data_methods.items():
         leaf_elms.append(ncutil.leaf_elm(key, valuef()))
     return leaf_elms
Пример #25
0
    def rpc_establish_subscription(self, session, rpc, *params):
        """ Source https://tools.ietf.org/id/draft-ietf-netconf-yang-push-19.html 
            +---x establish-subscription
        |  +---w input
        |  |  ...
        |  |  +---w (target)
        |  |  |  +--:(stream)
        |  |  |  |  ...
        |  |  |  +--:(yp:datastore)
        |  |  |     +---w yp:datastore                   identityref
        |  |  |     +---w (yp:selection-filter)?
        |  |  |        +--:(yp:by-reference)
        |  |  |        |  +---w yp:selection-filter-ref        
        |  |  |        |          selection-filter-ref
        |  |  |        +--:(yp:within-subscription)
        |  |  |           +---w (yp:filter-spec)?
        |  |  |              +--:(yp:datastore-subtree-filter)
        |  |  |              |  +---w yp:datastore-subtree-filter?   
        |  |  |              |          <anydata> {sn:subtree}?
        |  |  |              +--:(yp:datastore-xpath-filter)
        |  |  |                 +---w yp:datastore-xpath-filter?     
        |  |  |                         yang:xpath1.0 {sn:xpath}?
        |  |  | ...
        |  |  +---w (yp:update-trigger)
        |  |     +--:(yp:periodic)
        |  |     |  +---w yp:periodic!
        |  |     |     +---w yp:period         yang:timeticks
        |  |     |     +---w yp:anchor-time?   yang:date-and-time
        |  |     +--:(yp:on-change) {on-change}?
        |  |        +---w yp:on-change!
        |  |           +---w yp:dampening-period?   yang:timeticks
        |  |           +---w yp:sync-on-start?      boolean
        |  |           +---w yp:excluded-change*    change-type
        |  +--ro output
        |     +--ro id                            subscription-id
        |     +--ro replay-start-time-revision?   yang:date-and-time 
        |             {replay}?
        """
        # We have recieved an establish-subscription rpc
        # TODO validate more fields from the RPC

        logger.info("Received establish-subscription RPC")

        sub_type = None

        sid: int = -1
        sub = None
        root = rpc[0]
        nsmap = rpc[0].nsmap

        periodic_elm = root.find('yp:periodic', nsmap)
        on_change_elm = root.find('yp:on-change', nsmap)
        datastore_elm = root.find('yp:datastore', nsmap)
        datastore_xpath_filter_elm = root.find('yp:datastore-xpath-filter',
                                               nsmap)

        if periodic_elm is not None:
            period_elm = periodic_elm.find('yp:period', nsmap)
            period = int(period_elm.text)
            sub_type = Subscription.PERIODIC

            anchor_time_elm = periodic_elm.find('yp:anchor-time', nsmap)
            anchor_time = None
            if anchor_time_elm is not None:
                anchor_time = anchor_time_elm.text

        elif on_change_elm is not None:
            sub_type = Subscription.ON_CHANGE
        else:
            # Malformed request
            return ncutil.leaf_elm(
                'error',
                'Neither periodic nor on change found in establish-subscription request'
            )

        xpath_filter = datastore_xpath_filter_elm.text
        datastore = datastore_elm.text

        if sub_type == Subscription.PERIODIC:
            sid = self.get_next_sub_id()
            sub = Subscription(sid,
                               sub_type,
                               datastore,
                               period=period,
                               datastore_xpath_filter=xpath_filter,
                               raw=etree.tostring(
                                   rpc, pretty_print=True).decode('utf8'),
                               anchor_time=anchor_time)
            self.subscriptions[sid] = sub

        # Generate response
        res_map = {
            None: 'urn:ietf:params:xml:ns:yang:ietf-subscribed-notifications'
        }

        # id tag containing the subscription id
        res = etree.Element('id', nsmap=res_map)
        res.text = str(sid)

        logger.debug(etree.tostring(rpc, pretty_print=True).decode('utf8'))
        logger.debug(etree.tostring(res, pretty_print=True).decode('utf8'))

        if not self.datasource.xpath_exists(sub.datastore_xpath_filter):
            raise ValueError("XPath does not correspond to any data")

        PeriodicNotificationThread(sub, self.datasource, session)

        return res
Пример #26
0
 def rpc_my_cool_rpc(self, session, rpc, *params):
     data = ncutil.elm("data")
     data.append(ncutil.leaf_elm("pfx:result", "RPC result string"))
     return data
Пример #27
0
 def get_all_values():
     leaf_elms = []
     for key, valuef in get_data_methods.items():
         leaf_elms.append(ncutil.leaf_elm(key, valuef()))
     return leaf_elms
Пример #28
0
def main(args):

    if not args:
        return
    #print(type(args))
    #return

    #TODO: check if args is a valid IP

    nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")
    MODEL_NS = "urn:my-urn:my-model"
    nsmap_add('pfx', MODEL_NS)

    keyFileToSend = "python/cwCA/intermediate/certs/www.ap.controlware.com.cert.pem"
    privateKeyFile = "/usr/src/app/python/vendorCA/intermediate/private/www.ownership.vendor1.com.key.pem"

    fileString = getCertStringfromFile(keyFileToSend)

    sign = signString(privateKeyFile, b"password", fileString.encode('ascii'),
                      "sha256")

    #Encode signature so it can be send as a string
    sign_base64 = base64.b64encode(sign)
    utf8Signature = sign_base64.decode('utf-8')
    ownershipRPC = util.elm("ownership")
    cert = OpenSSL.crypto.load_certificate(
        OpenSSL.crypto.FILETYPE_PEM,
        getCertStringfromFile(
            '/usr/src/app/python/vendorCA/intermediate/certs/www.ownership.vendor1.com.cert.pem'
        ))
    #if verifyString(cert, sign, fileString.encode('ascii'),"sha256"):
    if verifyString(
            '/usr/src/app/python/vendorCA/intermediate/certs/www.ownership.vendor1.com.cert.pem',
            sign, fileString.encode('ascii'), "sha256"):
        ownerCertificate = util.subelm(ownershipRPC, "ownerCertificate")
        ownerCertificate.append(util.leaf_elm("certificate", fileString))
        #ownerCertificate.append(util.leaf_elm("certificateSignature", sign_base64))
        ownerCertificate.append(
            util.leaf_elm("certificateSignature", utf8Signature))

    bootstrapRPC = util.elm("bootstrap")
    bootInfo = util.subelm(bootstrapRPC, "bootInfo")

    #bootInfo_base64 = base64.b64encode(asnString)
    bytebootstrapArtifact = buildbootstrapArtifact()
    bootInfo_base64 = base64.b64encode(bytebootstrapArtifact)
    utf8BootInfo = bootInfo_base64.decode('utf-8')

    privateKeyFile = "/usr/src/app/python/cwCA/intermediate/private/www.ap.controlware.com.key.pem"
    sign = signString(privateKeyFile, b"password",
                      utf8BootInfo.encode('ascii'), "sha256")
    sign_base64 = base64.b64encode(sign)
    utf8Signature = sign_base64.decode('utf-8')

    bootInfo.append(util.leaf_elm("bootInfoASN", utf8BootInfo))

    if verifyString(
            '/usr/src/app/python/cwCA/intermediate/certs/www.ap.controlware.com.cert.pem',
            sign, utf8BootInfo.encode('ascii'), "sha256"):
        bootInfo.append(util.leaf_elm("bootInfoSignature", utf8Signature))

    #TODO: not hardcode
    session = NetconfSSHSession(args, "8300", "admin", "admin", debug=True)
    root, reply, replystring = session.send_rpc(ownershipRPC)
    root, reply, replystring = session.send_rpc(bootstrapRPC)
    session.close()

    dataElem = reply.find("nc:data", namespaces=NSMAP)
    x = dataElem.find("nc:result", namespaces=NSMAP)
    if x is not None:
        print(x.text)
    else:
        print("not found")
Пример #29
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        data = ncutil.elm("data")
        cont = ncutil.subelm(data, "interfaces")
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "Ethernet0/0"))
        listval.append(ncutil.leaf_elm("shutdown", "true"))
        listval.append(ncutil.leaf_elm("state", "down"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "Ethernet0/1"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval.append(ncutil.leaf_elm("state", "down"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "FastEthernet1/0"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval.append(ncutil.leaf_elm("state", "up"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "FastEthernet1/1"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval.append(ncutil.leaf_elm("state", "down"))

        return ncutil.filter_results(rpc, data, filter_or_none)
Пример #30
0
from netconf.client import NetconfSSHSession
from lxml import etree
import netconf.util as util
from netconf import nsmap_add, nsmap_update
from netconf import NSMAP

import re

nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")
MODEL_NS = "urn:my-urn:my-model"
nsmap_add('pfx', MODEL_NS)
#nsmap_update({'pfx': MODEL_NS})
data = util.elm("bootstrap")
redirect = util.subelm(data, "redirect-information")
boots_server = util.subelm(redirect, "bootstrap-server")
boots_server.append(util.leaf_elm("address", "172.17.0.1"))
boots_server.append(util.leaf_elm("port", "8300"))
boots_server.append(util.leaf_elm("trust_anchor", "undefined"))

onboard = util.subelm(data, "onboarding-information")
boot_img = util.subelm(onboard, "boot-image")
boot_img.append(util.leaf_elm("os-name", "IOS"))
boot_img.append(util.leaf_elm("os-version", "16.8"))
boot_img.append(util.leaf_elm("download-uri", "tftp://10.0.0.1/files"))
img_verification = util.subelm(boot_img, "image-verification")
img_verification.append(util.leaf_elm("hash-algorithm", "md5"))
img_verification.append(util.leaf_elm("hash-value", "12345678"))

onboard.append(util.leaf_elm("configuration-handling", "append"))
onboard.append(util.leaf_elm("pre-configuration-script", "pre.py"))
onboard.append(util.leaf_elm("configuration", "tbd"))