Пример #1
0
    def get_count_port_errors(self, port, curr):
        """ Количество ошибок на порту """

        oid_errors = 'iso.3.6.1.2.1.2.2.1.'

        counts = (14, 20)

        if_index = self.get_snmp_port_number(port)
        if not if_index or if_index < 0:
            return dumps({
                'status' : Status.ERROR
            })
        # формируем запрос со всеми оидами
        oids = VarList()
        for index in counts:
            oid = Varbind('{0}{1}.{2}'.format(oid_errors, index, if_index))
            oids.append(oid)

        # лист с количеством ошибок на каждом счетчике
        res = self.sess.get(oids)

        # суммируем ошибки
        errors = 0
        for count in res:
            errors += int(count)

        delta = 0
        if curr > 0:
            delta = errors - int(curr)

        return dumps({
            'status' : Status.SUCCESS,
            'errors' : errors,
            'delta'  : delta
        })
Пример #2
0
    def cable_test(self, port):
        """ Кабельная диагностика """
        oid_diag = 'iso.3.6.1.4.1.2011.5.25.31.1.1.7.1.'

        port = self.get_snmp_port_number(port)
        if not port or port < 0:
            return dumps({
                'status' : Status.ERROR
            })

        count = 10
        for c in xrange(count):
            oids = VarList()
            # 2 - status, 3 - length
            for index in 2, 3:
                oid_str = '{0}{1}.{2}'.format(oid_diag, index, port)
                oid = Varbind(oid_str)
                oids.append(oid)

            res = self.sess.get(oids)

            if not res:
                msg = 'not status answer {0}:{1}'.format(self.ip, port)
                print(msg)
                return dumps({
                    'status' : Status.ERROR,
                    'msg'    : msg
                })

            if res[1] not in ('150', '204'):
                break
            elif c + 1 == count:
                return dumps({
                    'status' : Status.CBNOINFO
                })

        data = {}
        status = int(res[0]) - 1
        p1, col1 = Switch.convert_descr(str(status))
        len1 = int(res[1])
        data['p1col'] = col1
        data['p1st'] = p1
        data['p1len'] = len1

        return dumps({
            'status': Status.SUCCESS,
            'data'  : data
        })
Пример #3
0
    def get_count_port_errors(self, port, curr):
        """ Считывает по snmp количество ошибок на порту клиента
        Принимает массив с айпи свитча (ip), снмп-портом (port) и текущим количеством ошибок (cur)
        Возвращает количество ошибок и дельту, если в запросе было указано
        количество ошибок уже """

        # dlink stored info about ports
        oid_errors = 'iso.3.6.1.2.1.2.2.1.'

        counts = (14, 20)

        # Может быть не надо, но запрос быстрый, так что оставим
        if_index = self.get_snmp_port_number(port)
        if not if_index or if_index < 0:
            return dumps({
                'status' : Status.ERROR
            })
        # формируем запрос со всеми оидами
        oids = VarList()
        for index in counts:
            oid = Varbind('{0}{1}.{2}'.format(oid_errors, index, if_index))
            oids.append(oid)

        # лист с количеством ошибок на каждом счетчике
        res = self.sess.get(oids)

        # суммируем ошибки
        errors = 0
        for count in res:
            errors += int(count)

        delta = 0
        if curr > 0:
            delta = errors - int(curr)

        return dumps({
            'status' : Status.SUCCESS,
            'errors' : errors,
            'delta'  : delta
        })
Пример #4
0
    def get_count_port_errors(self, port, curr):
        """ Считывает по snmp количество ошибок на порту клиента
        Принимает массив с айпи свитча (ip), снмп-портом (port) и текущим количеством ошибок (cur)
        Возвращает количество ошибок и дельту, если в запросе было указано
        количество ошибок уже Huawei CX200 не поддерживается, поэтому сразу возвращает что это CX200 """

# http://support.huawei.com/enterprise/docinforeader.action?contentId=DOC1000027252&idPath=7919710|9856733|7923144|16561 (01-41 HUAWEI-IF-EXT-MIB)
        oid_errors = 'iso.3.6.1.4.1.2011.5.25.41.1.6.1.1.'

# http://support.huawei.com/enterprise/docinforeader.action?contentId=DOC1000027252&idPath=7919710|9856733|7923144|16561 (01-41 HUAWEI-IF-EXT-MIB)
        counts = (11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33)

        if_index = self.get_snmp_port_number(port)
        if not if_index or if_index < 0:
            return dumps({
                'status' : Status.ERROR
            })
        # формируем запрос со всеми оидами
        oids = VarList()
        for index in counts:
            oid = Varbind('{0}{1}.{2}'.format(oid_errors, index, if_index))
            oids.append(oid)

        # лист с количеством ошибок на каждом счетчике
        res = self.sess.get(oids)

        # суммируем ошибки
        errors = 0
        for count in res:
            errors += int(count)

        delta = 0
        if curr > 0:
            delta = errors - int(curr)

        return dumps({
            'status' : Status.SUCCESS,
            'errors' : errors,
            'delta'  : delta
        })
Пример #5
0
    def cable_test_all(self):
        """ Возвращает результат кабдиага на всех портах кроме активных и где активный договор """
        # получим список всех 100мб портов
        oid_typeport = 'iso.3.6.1.2.1.2.2.1.3'
        oid_status = 'iso.3.6.1.2.1.2.2.1.8'

        var_types = self.sess.bulkwalk(oid_typeport)
        if not var_types:
            msg = 'Предположительно свитч лежит!'
            return dumps({
                'status' : Status.ERROR,
                'msg'    : msg
            })

        var_status = self.sess.bulkwalk(oid_status)
        if not var_status:
            msg = 'Предположительно свитч лежит!'
            return dumps({
                'status' : Status.ERROR,
                'msg'    : msg
            })

        if len(var_types) != len(var_status):
            print('len not equal on switch {0}'.format(self.ip))
            return dumps({
                'status' : Status.ERROR
            })

        t = {int(i.split('.')[-1]): int(y) for (i, j), (x, y) in zip(var_types, var_status) if int(j) == 6}
        data = {i + 1: k for i, (k, v) in enumerate(sorted(t.iteritems())) if v == 2}

        oid_dlink = 'iso.3.6.1.4.1.171.12.58.1.1.1.'
        rw_cabdiag = 12

        oids = []
        for port in data.values():
            oid_str = '{0}{1}.{2}'.format(oid_dlink, rw_cabdiag, port)
            oid = Varbind(oid_str, '', 1, 'INTEGER')
            oids.append(oid)

        for oid in oids:
            self.sess.set(VarList(oid))

        count = 0
        status = ''
        sleep_time = 0.5
        # ждем пока не вернет 3 (ready for test) завершения теста 6/sleep_time = 3sec
        oid = '{0}{1}'.format(oid_dlink, rw_cabdiag)
        while not status and not all(val == '3' for tag, val in status) and count < 6:
            status = self.sess.bulkwalk(oid)
            sleep(sleep_time)
            count += 1

        for k, port in data.iteritems():
            # 4-7 status pair 1-4, 8-11 length pair 1-4
            oids = VarList()
            for index in 4, 5, 8, 9:
                oid = Varbind('{0}{1}.{2}'.format(oid_dlink, index, port))
                oids.append(oid)

            res = self.sess.get(oids)

            # частный случай, длинк не может промерить кабель, так как он вставлен в активное оборудование
            if all(x == '0' for x in res):
                data[k] = {
                    'status' : Status.CBNOINFO
                }
                continue
            tmp = {}
            p1, col1 = Switch.convert_descr(res[0])
            p2, col2 = Switch.convert_descr(res[1])
            len1 = int(res[2])
            len2 = int(res[3])
            tmp['p1col'] = col1
            tmp['p1st'] = p1
            tmp['p1len'] = len1
            tmp['p2col'] = col2
            tmp['p2st'] = p2
            tmp['p2len'] = len2

            data[k] = {
                'status': Status.SUCCESS,
                'data'  : tmp
            }

        return dumps({
            'status': Status.SUCCESS,
            'data'  : data
        })
Пример #6
0
    def cable_test(self, port):
        oid_dlink = 'iso.3.6.1.4.1.171.12.58.1.1.1.'
        rw_cabdiag = 12
        port = self.get_snmp_port_number(port)
        if not port or port < 0:
            return dumps({
                'status' : Status.ERROR
            })
        oid_str = '{0}{1}.{2}'.format(oid_dlink, rw_cabdiag, port)
        oid = VarList(Varbind(oid_str, '', 1, 'INTEGER'))

        status = self.sess.set(oid)

        if not status:
            msg = 'not status answer {0}:{1}'.format(self.ip, port)
            print(msg)
            return dumps({
                'status' : Status.ERROR,
                'msg'    : msg
            })

        count = 0
        status = 2
        sleep_time = 0.5
        # ждем пока не вернет 3 (ready for test) завершения теста 6/sleep_time = 3sec
        oid = VarList(Varbind(oid_str))
        while status != '3' and count < 6:
            status, = self.sess.get(oid)
            sleep(sleep_time)
            count += 1

        # формируем запрос со всеми оидами
        oids = VarList()
        # 4-7 status pair 1-4, 8-11 length pair 1-4
        for index in 4, 5, 8, 9:
            oid = Varbind('{0}{1}.{2}'.format(oid_dlink, index, port))
            oids.append(oid)

        # лист с количеством ошибок на каждом счетчике
        res = self.sess.get(oids)

        # частный случай, длинк не может промерить кабель, так как он вставлен в активное оборудование
        if all(x == '0' for x in res):
            return dumps({
                'status' : Status.CBNOINFO
            })
        data = {}
        p1, col1 = Switch.convert_descr(res[0])
        p2, col2 = Switch.convert_descr(res[1])
        len1 = int(res[2])
        len2 = int(res[3])
        data['p1col'] = col1
        data['p1st'] = p1
        data['p1len'] = len1
        data['p2col'] = col2
        data['p2st'] = p2
        data['p2len'] = len2

        return dumps({
            'status': Status.SUCCESS,
            'data'  : data
        })
Пример #7
0
    def get_snmp_port_status(self, port):
        ''' Принимает айпи свитча и порт Возвращает его статус '''

        if_index = self.get_snmp_port_number(port)

        # switch down by snmp
        if not if_index:
            stport = 'muted'
            stswitch = 'danger'
            # если свитч не ответил по снмп, попробуем пингануть
            r = self.__available_by_system_ping()
            if r:
                # свитч в апе, проблема в снмп коммунити
                stswitch = 'warning'
            return dumps({
                'isup'          : 0,
                'statusswitch'  : stswitch,
                'statusport'    : stport,
                'ip'            : self.ip,
                'port'          : port
            })
        # гиговый порт
        if if_index < 0:
            return dumps({
                'status' : Status.ERROR
            })
        # список портов
        oid_ports = 'iso.3.6.1.2.1.2.2.1.'
        oids = VarList()
        # 7 - admin status, 8 - oper status, 5 - port speed http://www.opennet.ru/base/cisco/cisco_snmp.txt.html
        for index in 7, 8, 5:
            oid = Varbind('{0}{1}.{2}'.format(oid_ports, index, if_index))
            oids.append(oid)

        # лист со статусом портов, административный и оперативный, 1 - up, 2 - down
        ret = self.sess.get(oids)
        admin = 0 if ret[0] == '2' else 1
        oper = ret[1]
        speed = int(ret[2]) / 1000000

        # None - error, 1 = port up, 2 = port down
        sw_status = 'success'
        port_status = 'muted'
        if not oper:
            port_status = 'muted'
        elif oper == '2':
            port_status = 'danger'
        elif oper == '1':
            if speed == 100:
                port_status = 'success'
            else:
                port_status = 'warning'

        return dumps({
            'isup'          : 1,
            'statusswitch'  : sw_status,
            'statusport'    : port_status,
            'statusadmin'   : admin,
            'ip'            : self.ip,
            'port'          : port
        })