summaryrefslogtreecommitdiff
path: root/examples/smi/agent/custom-managed-object.py
blob: f1af0ae38a26b9911257b88ef930dfa87abf817a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Implementing MIB objects
++++++++++++++++++++++++

This script explains how SNMP Agent application could model
real-world data as Managed Objects defined in MIB.

"""#
from pysnmp.smi import builder

# MIB Builder is normally pre-created by SNMP engine
mibBuilder = builder.MibBuilder()

#
# This may be done in a stand-alone file and then loaded up
# by SNMP Agent
#

# A base class for a custom Managed Object
MibScalarInstance, = mibBuilder.importSymbols(
    'SNMPv2-SMI', 'MibScalarInstance'
)

# Managed object specification
sysLocation, = mibBuilder.importSymbols('SNMPv2-MIB', 'sysLocation')


# Custom Managed Object
class MySysLocationInstance(MibScalarInstance):
    # noinspection PyUnusedLocal
    def readGet(self, varBind, **context):
        # Just return a custom value
        return varBind[0], self.syntax.clone('The Leaky Cauldron')


sysLocationInstance = MySysLocationInstance(
    sysLocation.name, (0,), sysLocation.syntax
)

# Register Managed Object with a MIB tree
mibBuilder.exportSymbols(
    # '__' prefixed MIB modules take precedence on indexing
    '__MY-LOCATION-MIB', sysLocationInstance=sysLocationInstance
)

if __name__ == '__main__':
    #
    # This is what is done internally by Agent.
    #
    from pysnmp.smi import instrum, exval

    mibInstrum = instrum.MibInstrumController(mibBuilder)

    def cbFun(varBinds, **context):
        for oid, val in varBinds:
            if exval.endOfMib.isSameTypeWith(val):
                context['state']['stop'] = True
            print('%s = %s' % ('.'.join([str(x) for x in oid]), not val.isValue and 'N/A' or val.prettyPrint()))

        context['state']['varBinds'] = varBinds

    context = {
        'cbFun': cbFun,
        'state': {
            'varBinds': [((1, 3, 6), None)],
            'stop': False
        }
    }

    print('Remote manager read access to MIB instrumentation (table walk)')
    while not context['state']['stop']:
        mibInstrum.readNextVars(*context['state']['varBinds'], **context)
    print('done')