Exemple #1
0
def get_mib_view_controller():
    try:
        # Try and load MIB modules even from the users uploads
        mvc = MibViewController(MibBuilder().loadModules())
    except SmiError:
        # If somehow the user managed to bypass the validation and
        # upload the same MIB twice an SmiError will be thrown.
        logging.warning('The user has uploaded duplicate MIB files, ignoring all user upload MIB files!')
        
        # In which case we should try again without loading the user
        # uploaded MIB files
        mb = MibBuilder()
        mib_paths = mb.getMibPath()
        try:
            # Identify the position of the user upload path
            i = mib_paths.index(os.environ['PYSNMP_MIB_DIR'])
        except (KeyError, ValueError):
            return None
        else:
            # Remove the user upload path from the paths we are going
            # to use.
            mib_paths = mib_paths[:i] + mib_paths[i+1:]
            mb.setMibPath(*mib_paths)
            
            # Try again
            try:
                mvc = MibViewController(mb.loadModules())
            except SmiError:
                # Nothing we can do now, its a problem with "pysnmp"
                logging.error('There is a problem with MIB store in "pysnmp".')
                return None
    return mvc
    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, { mibInfo.name: symtable }, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        mibBuilder = MibBuilder()
        mibBuilder.loadTexts = True

        self.ctx = { 'mibBuilder': mibBuilder }

        exec(codeobj, self.ctx, self.ctx)
Exemple #3
0
    def setUp(self):
        ast = parserFactory()().parse(self.__class__.__doc__)[0]
        mibInfo, symtable = SymtableCodeGen().genCode(ast, {}, genTexts=True)
        self.mibInfo, pycode = PySnmpCodeGen().genCode(ast, {mibInfo.name: symtable}, genTexts=True)
        codeobj = compile(pycode, 'test', 'exec')

        mibBuilder = MibBuilder()
        mibBuilder.loadTexts = True

        self.ctx = {'mibBuilder': mibBuilder}

        exec (codeobj, self.ctx, self.ctx)
Exemple #4
0
def get_mib_view_controller():
    try:
        # Try and load MIB modules even from the users uploads
        mvc = MibViewController(MibBuilder().loadModules())
    except SmiError:
        # If somehow the user managed to bypass the validation and
        # upload the same MIB twice an SmiError will be thrown.
        logging.warning(
            'The user has uploaded duplicate MIB files, ignoring all user upload MIB files!'
        )

        # In which case we should try again without loading the user
        # uploaded MIB files
        mb = MibBuilder()
        mib_paths = mb.getMibPath()
        try:
            # Identify the position of the user upload path
            i = mib_paths.index(os.environ['PYSNMP_MIB_DIR'])
        except (KeyError, ValueError):
            return None
        else:
            # Remove the user upload path from the paths we are going
            # to use.
            mib_paths = mib_paths[:i] + mib_paths[i + 1:]
            mb.setMibPath(*mib_paths)

            # Try again
            try:
                mvc = MibViewController(mb.loadModules())
            except SmiError:
                # Nothing we can do now, its a problem with "pysnmp"
                logging.error('There is a problem with MIB store in "pysnmp".')
                return None
    return mvc
Exemple #5
0
    ObjectType,
    SnmpEngine,
    UdpTransportTarget,
    UsmUserData,
    usmDESPrivProtocol,
    usmHMACMD5AuthProtocol,
)
from pysnmp.hlapi.asyncore.cmdgen import lcd
from pysnmp.hlapi.transport import AbstractTransportTarget
from pysnmp.proto.rfc1902 import Counter32, Counter64, Gauge32, Integer, Integer32, ObjectName, Unsigned32
from pysnmp.smi.builder import DirMibSource, MibBuilder
from pysnmp.smi.exval import endOfMibView, noSuchInstance, noSuchObject
from pysnmp.smi.view import MibViewController

# Additional types that are not part of the SNMP protocol (see RFC 2856).
CounterBasedGauge64, ZeroBasedCounter64 = MibBuilder().importSymbols(
    'HCNUM-TC', 'CounterBasedGauge64', 'ZeroBasedCounter64')

# Cleanup.
del MibBuilder

__all__ = [
    'AbstractTransportTarget',
    'Asn1Type',
    'DirMibSource',
    'CommunityData',
    'ContextData',
    'CounterBasedGauge64',
    'endOfMibView',
    'hlapi',
    'lcd',
    'MibViewController',
def main(warning, critical, debug, interface, type, community="public",
        host="localhost", port=161, *metrics):
    if debug:
        print "Arguments as parsed by plac:"
        print

        pprint.pprint(locals())

    modules = MibBuilder().loadModules('RFC1213-MIB')
    rfc1213 = MibViewController(modules)

    values = {}
    oids = []

    if not interface:
        print "CRITICAL: No interface specified!"
        sys.exit(EXITCODE['CRITICAL'])

    if not metrics:
        print "CRITICAL: No metrics specified!"
        sys.exit(EXITCODE['CRITICAL'])

    for metric in metrics:
        if metric not in METRIC_LIST:
            print "CRITICAL: %s not in metric list!" % metric
            sys.exit(EXITCODE['CRITICAL'])

        oid = rfc1213.getNodeNameByDesc(metric)[0]
        oids.append(oid + (int(interface),))

    try:
        cmd = cmdgen.CommandGenerator()

        errorIndication, errorStatus, \
        errorIndex, table = cmd.getCmd(
            cmdgen.CommunityData('nagios', community),
            cmdgen.UdpTransportTarget((host, port)),
            *oids)

        if errorIndication:
            print "CRITICAL: %s" % errorIndication
            sys.exit(EXITCODE['CRITICAL'])
        else:
            if errorStatus:
                print "CRITICAL: %s" % errorStatus.prettyPrint()
                sys.exit(EXITCODE['CRITICAL'])
            else:
                for row in table:
                    oid, value = row

                    p_oid, p_label, p_suffix = rfc1213.getNodeName(oid)

                    p_type = '.'.join(p_label[9:])
                    p_interface = '.'.join(str(i) for i in p_suffix)

                    # TODO: Add code path to print interface list
                    if debug:
                        if p_type == 'ifDescr':
                            print "%s.%s: %s" % (p_type, p_interface, value)

                    if p_type in metrics and p_interface == interface:
                        if debug:
                            print "%s.%s: %s" % (p_type, p_interface, value)

                        values[p_type] = value

    except socket.gaierror:
        print "CRITICAL: Unable to connect to the server."
        sys.exit(EXITCODE['CRITICAL'])

    status = 3

    if not warning and not critical:
        # Informational only, i.e. for pnp4nagios
        status = 0
    elif type in ['be-higher-than', 'be-lower-than']:
        warning = float(warning)
        critical = float(critical)

        statuses = []

        for key, value in values.items():
            value = float(value)

            statuses.append(test_in_range(value, warning, critical,
                type == 'be-lower-than'))

        status = max(statuses)
    elif type == 'within-range':
        # Ranges like 7.1-8.9. Overkill? Maybe.
        # TODO: Add support for Nagios-style ranges.
        re_range = re.compile("(\d+\.{0,1}\d*)[\- ]+(\d+\.{0,1}\d*)")

        try:
            warning_min, warning_max = map(float,
                    re_range.search(warning).groups())
            critical_min, critical_max = map(float,
                    re_range.search(critical).groups())
        except:
            print "%s CRITICAL: Error parsing arguments." % SERVICE

            sys.exit(EXITCODE['CRITICAL'])

        value = float(value)

        status = max(test_in_range(value, warning_min, critical_min, False),
                     test_in_range(value, warning_max, critical_max))
    elif type in ['must-have-regex', 'must-not-have-regex']:
        re_warning = re_critical = None

        try:
            if warning:
                re_warning = re.compile(warning)
            if critical:
                re_critical = re.compile(critical)
        except:
            print "%s CRITICAL: Your regular expression was invalid." % SERVICE
            sys.exit(2)

        status = 0

        if re_warning:
            if (re_warning.search(value) is not None) == \
                    (type == 'must-not-have-regex'):
                status = 1

        if re_critical:
            if (re_critical.search(value) is not None) == \
                    (type == 'must-not-have-regex'):
                status = 2

    if debug:
        pprint.pprint(values)

    print "%s %s: %s|%s" % (SERVICE, STATUSES[status], format_values(values),
            format_perfdata(metrics, values, warning, critical))

    sys.exit(status)