Beispiel #1
0
    def test_not_authorized(self):
        f = 'not_authorized.xml'
        xml_reader = XMLReader('test.de', 'test', 'test')

        with responses.RequestsMock() as rsps:
            rsps.add(responses.GET,
                     xml_reader.build_request_url(),
                     body=utils.read_xml(f),
                     status=200,
                     content_type='document',
                     match_querystring=True)
            with pytest.raises(CheckError):
                xml_reader.read()
Beispiel #2
0
    def test_xml_exception_404(self):
        f = 'diskspace.xml'
        xml_reader = XMLReader('test.de', 'test', 'test')

        with responses.RequestsMock() as rsps:
            rsps.add(responses.GET,
                     xml_reader.build_request_url(),
                     body=utils.read_xml(f),
                     status=404,
                     content_type='document',
                     match_querystring=True)
            with pytest.raises(CheckError):
                xml_reader.read()
Beispiel #3
0
class Thermal(np.Resource):
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><system><environmentals><thermal>' \
                   '</thermal></environmentals></system></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create thermal metrics.

        :return: a disk space metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        entrys = soup.find_all('entry')
        for entry in entrys:
            temp = entry.DegreesC.text
            _log.debug('Temperature: %s', temp)
            maxt = entry.max.text
            _log.debug('Max Temperature: %s', maxt)
            mint = entry.min.text
            _log.debug('Min Temperature: %s', mint)
            desc = entry.description.text
            _log.debug('Description: %s', desc)
            yield np.Metric(desc,
                            float(temp),
                            min=float(mint),
                            max=float(maxt),
                            context='temperature')
class Antivirus(np.Resource):
    """
    Will fetch the antivirus definition date from the REST API and returns
    a warning if the definition date is between the value of warning (e. g. 1)
    and critical (e. g. 2).
    """
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><system><info></info></system></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create antivirus metrics.

        :return: antivirus metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        result = soup.result
        av_release_date = Finder.find_item(result,
                                           'av-release-date').split(' ')[0]
        # 2019/01/06  04:03:50
        now = get_now()
        date_object = datetime.strptime(av_release_date, '%Y/%m/%d')
        difference = now - date_object
        _log.info('Difference: %s days (%s -- %s)' %
                  (difference.days, av_release_date, now))

        return [
            np.Metric('av-release-days',
                      difference.days,
                      context='av-release-days')
        ]
Beispiel #5
0
class UserAgent(np.Resource):
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><user><user-id-agent><state>all</state>' \
                   '</user-id-agent></user></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create user agent metrics.

        :return: a user agent metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        s = soup.result.string.strip()
        useragents = s.split('\n\n')

        for useragent in useragents:
            agent_details = useragent.split('\n')
            if (len(agent_details) != 31) or not (agent_details[0].startswith('Agent')):
                raise CheckError('Unexpected query result!')

            name = agent_details[0]
            status = agent_details[1].split(':')[1].strip()
            last_heared = int(agent_details[20].split(':')[1].strip())

            _log.info('Checking %s ', name)
            _log.info('Found status %s', status)
            _log.info('Last heared: %i seconds ago', last_heared)

            yield np.Metric(name, status, context='agent_connected')
            yield np.Metric(name, last_heared, context='agent_last_heared')
Beispiel #6
0
    def test_finder2(self):
        f = 'load.xml'
        xml_reader = XMLReader('test.de', 'test', 'test')

        with responses.RequestsMock() as rsps:
            rsps.add(responses.GET,
                     xml_reader.build_request_url(),
                     body=utils.read_xml(f),
                     status=200,
                     content_type='document',
                     match_querystring=True)
            xml_response = xml_reader.read()
            with pytest.raises(CheckError):
                Finder.find_item(xml_response, 'test')
Beispiel #7
0
    def test_finder(self):
        f = 'load.xml'
        xml_reader = XMLReader('test.de', 'test', 'test')

        with responses.RequestsMock() as rsps:
            rsps.add(responses.GET,
                     xml_reader.build_request_url(),
                     body=utils.read_xml(f),
                     status=200,
                     content_type='document',
                     match_querystring=True)
            xml_response = xml_reader.read()
            found = Finder.find_item(xml_response, 'coreid')
            assert '0' == found
Beispiel #8
0
    def test_xml_read_response(self):
        f = 'diskspace.xml'
        xml_reader = XMLReader('test.de', 'test', 'test')

        with responses.RequestsMock() as rsps:
            rsps.add(responses.GET,
                     xml_reader.build_request_url(),
                     body=utils.read_xml(f),
                     status=200,
                     content_type='document',
                     match_querystring=True)
            xml_response = xml_reader.read()
            text = xml_response.response['status']
            assert text == "success"
Beispiel #9
0
class Bgp(np.Resource):
    """
    Will fetch the bgp informations (routes and peers) from the REST API and returns
    a warning if the result is lesser the value of warning (e. g. 1)
    and critical (e. g. 2).
    """
    def __init__(self, host, token, mode, peer):
        self.host = host
        self.token = token
        self.mode = mode
        self.peer = peer
        if peer is not None:
            self.cmd = '<show><routing><protocol><bgp><peer><peer-name>%s</peer-name></peer></bgp></protocol></routing></show>' % self.peer
        else:
            self.cmd = '<show><routing><summary></summary></routing></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create bgp metrics.

        :return: bgp metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        result = soup.result
        _log.debug('XML Result: \n%s', str(result))
        if self.mode == "routes":
            for item in result.find_all('BGP-Routes'):
                bgp_routes = int(Finder.find_item(item, 'total'))
            _log.info('BGP Routes: %s' % bgp_routes)
            return [np.Metric('bgp-routes-count', bgp_routes, context='bgp')]
        elif self.mode == "peers":
            if self.peer:
                peer_status = Finder.find_item(result, 'status')
                peer_status_duration = Finder.find_item(
                    result, 'status-duration')
                return [
                    np.Metric('peer-status', peer_status, context='bgp'),
                    np.Metric('peer-status-duration',
                              "%ss" % peer_status_duration,
                              context='bgp')
                ]
            else:
                for item in result.find_all('bgp'):
                    peer_count = int(Finder.find_item(item, 'peer-count'))
                _log.info('BGP Peers: %s' % peer_count)
                return [np.Metric('peer-count', peer_count, context='bgp')]
Beispiel #10
0
def get_all(host, token):
    """
    Get all interfaces name.

    :return: array of interface names
    """
    interfaces = []
    cmd = '<show><counter><interface>all</interface></counter></show>'
    xml_obj = XMLReader(host, token, cmd)
    soup = xml_obj.read()
    ifnet = soup.find('ifnet')

    for item in ifnet.find_all('entry'):
        ifname = Finder.find_item(item, 'name')
        interfaces.append(str(ifname))

    return interfaces
class Certificate(np.Resource):
    """
    Will fetch the certificates from the REST API and returns a warning if
    the remaining days of the certificate is between the value of warning
    (e. g. 20) and critical (e. g. 0).

    If a certificate has been revoked or excluded, no warning will appear.
    """

    def __init__(self, host, token, exclude):
        self.host = host
        self.token = token
        self.cmd = '<show><config><running>' \
                   '<xpath>shared/certificate</xpath>' \
                   '</running></config></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)
        self.exclude = str(exclude).split(",")

    def probe(self):
        """
        Querys the REST-API and create certificate metrics.

        :return: a certificate metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()

        certificates = soup.find_all('entry')

        for certificate in certificates:
            not_valid_after = Finder.find_item(certificate,
                                             'not-valid-after').replace(
                "GMT", "").strip()
            date_object = datetime.strptime(not_valid_after, '%b %d %H:%M:%S %Y')
            difference = date_object - get_now()
            _log.debug('Certificate %s difference: %s days' % (
                certificate.get('name'), difference.days))
            try:
                status = Finder.find_item(certificate, 'status')
            except np.CheckError:
                status = ""
            if certificate.get('name') not in self.exclude:
                if status != "revoked":
                    yield np.Metric(certificate.get('name'), difference.days,
                                    context='certificates')
Beispiel #12
0
class DiskSpace(np.Resource):
    """Reads the used disk space of the Palo Alto Firewall System."""
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><system><disk-space><%2Fdisk-space><%2Fsystem' \
                   '><%2Fshow>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create disk space metrics.

        :return: a disk space metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        available_hdds = re.findall('(sda\d.*?)(?=/)', soup.result.string)
        for hdd in available_hdds:
            sda = re.findall('(sda\d)', hdd)[0]
            percent = int(re.findall('([0-9]+%)', hdd)[0].replace("%", ""))
            yield np.Metric(sda, percent, '%', context='diskspace')
Beispiel #13
0
class SessInfo(np.Resource):
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><session><info></info></session></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create session info metrics.

        :return: a sessioninfo metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        result = soup.result
        maxsess = int(Finder.find_item(result, 'num-max'))
        actsess = int(Finder.find_item(result, 'num-active'))
        throughput = int(Finder.find_item(result, 'kbps'))

        return [np.Metric('session', actsess, min=0, max=maxsess, context='session'),
                np.Metric('throughput_kbps', throughput, min=0, context='throughput')]
class Environmental(np.Resource):
    """Reads the used disk space of the Palo Alto Firewall System."""
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><system><environmentals>' \
                   '</environmentals></system></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create disk space metrics.

        :return: a disk space metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        entrys = soup.find_all('entry')
        for entry in entrys:
            if entry.alarm.text == 'True':
                _log.debug('Alarm found: %s' % entry.description)
                yield np.Metric(entry.description.text, True, context='alarm')
            yield np.Metric(entry.description.text, False, context='alarm')
class Load(np.Resource):
    def __init__(self, host, token):
        self.host = host
        self.token = token
        self.cmd = '<show><running><resource-monitor><minute><last>1<%2Flast' \
                   '>' \
                   '<%2Fminute><%2Fresource-monitor><%2Frunning><%2Fshow>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create load metrics.

        :return: a load metric.
        """
        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())
        soup = self.xml_obj.read()
        cpuavg = soup.find('cpu-load-average')

        for entry in cpuavg.find_all('entry'):
            coreid = int(Finder.find_item(entry, 'coreid'))
            cpu_load = float(Finder.find_item(entry, 'value'))
            yield np.Metric('CPU%d' % coreid, cpu_load, '%', min=0, max=100,
                            context='load')
Beispiel #16
0
class Throughput(np.Resource):
    """
    A throughput resource.
    """
    def __init__(self, host, token, interface_name):
        self.host = host
        self.token = token
        self.interface_name = interface_name
        self.cmd = '<show><counter><interface>' + str(
            self.interface_name) + '</interface></counter></show>'
        self.xml_obj = XMLReader(self.host, self.token, self.cmd)

    def probe(self):
        """
        Querys the REST-API and create throughput metrics.

        :return: a throughput metric.
        """

        _log.info('Reading XML from: %s', self.xml_obj.build_request_url())

        api_outbytes, api_inbytes = 0, 0

        current_time = get_time()
        soup = self.xml_obj.read()
        ifnet = soup.find('ifnet')

        try:
            for item in ifnet.find_all('entry'):
                api_inbytes = Finder.find_item(item, 'ibytes')
                api_outbytes = Finder.find_item(item, 'obytes')
        except:
            api_inbytes = "0"
            api_outbytes = "0"

        _log.debug('Path to statefile: %r' % get_statefile_path())
        with np.Cookie(get_statefile_path()) as cookie:

            old_inbytes = cookie.get(self.host + self.interface_name + 'i',
                                     api_inbytes)
            old_outbytes = cookie.get(self.host + self.interface_name + 'o',
                                      api_outbytes)
            old_time = cookie.get(self.host + self.interface_name + 't',
                                  current_time)

            if not api_inbytes or not api_outbytes or float(
                    api_inbytes) < 0 or float(api_outbytes) < 0:
                raise np.CheckError('Couldn\'t get a valid value!')

            cookie[self.host + self.interface_name + 'i'] = api_inbytes
            cookie[self.host + self.interface_name + 'o'] = api_outbytes
            cookie[self.host + self.interface_name + 't'] = current_time

        if float(api_inbytes) < float(old_inbytes) or float(
                api_outbytes) < float(old_outbytes):
            raise np.CheckError(
                'Couldn\'t get a valid value: Found throughput less then old!')

        diff_time = int(current_time) - int(old_time)
        if diff_time > 0:
            in_bits_per_second = round(
                ((float(api_inbytes) - float(old_inbytes)) / diff_time) * 8, 2)
            out_bits_per_second = round(
                ((float(api_outbytes) - float(old_outbytes)) / diff_time) * 8,
                2)
        else:
            raise np.CheckError(
                'Difference between old timestamp and new timestamp is less '
                'or equal 0: If it is the first time you run the script, '
                'please execute it again!')

        return [
            np.Metric('in_bps_' + str(self.interface_name),
                      in_bits_per_second,
                      min=0),
            np.Metric('out_bps_' + str(self.interface_name),
                      out_bits_per_second,
                      min=0)
        ]