File: snmptranslate.py

package info (click to toggle)
python-pysnmp4-apps 0.4.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 284 kB
  • sloc: python: 2,397; makefile: 3
file content (202 lines) | stat: -rwxr-xr-x 6,587 bytes parent folder | download
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/env python
#
# This file is part of pysnmp-apps software.
#
# Copyright (c) 2005-2016, Ilya Etingof <ilya@glas.net>
# License: http://pysnmp.sf.net/license.html
#
# Command-line MIB browser
#
import sys, traceback
from pyasn1.type import univ
from pysnmp.entity import engine
from pysnmp.proto import rfc3412
from pysnmp.smi import builder
from pysnmp_apps.cli import main, pdu, mibview, base
from pysnmp.smi.error import NoSuchObjectError
from pysnmp import error
from pyasn1.type import univ

def getUsage():
    return "Usage: %s [OPTIONS] <PARAMETERS>\n\
%s%s\
TRANSLATE options:\n\
   -T TRANSOPTS   Set various options controlling report produced:\n\
              d:  print full details of the given OID\n\
              a:  dump the loaded MIB in a trivial form\n\
              l:  enable labeled OID report\n\
              o:  enable OID report\n\
              s:  enable dotted symbolic report\n\
%s\n" % (sys.argv[0],
         main.getUsage(),
         mibview.getUsage(),
         pdu.getReadUsage())

# Construct c/l interpreter for this app

class Scanner(mibview.MibViewScannerMixIn,
              pdu.ReadPduScannerMixIn,
              main.MainScannerMixIn,
              base.ScannerTemplate):
    def t_transopts(self, s):
        r' -T '
        self.rv.append(base.ConfigToken('transopts'))

class Parser(mibview.MibViewParserMixIn,
             pdu.ReadPduParserMixIn,
             main.MainParserMixIn,
             base.ParserTemplate):
    def p_transOptions(self, args):
        '''
        Cmdline ::= Options whitespace Params
        Cmdline ::= Options Params

        Option ::= TranslateOption

        TranslateOption ::= transopts whitespace string
        TranslateOption ::= transopts string

        '''

class __Generator(base.GeneratorTemplate):
    def n_TranslateOption(self, cbCtx, node):
        snmpEngine, ctx = cbCtx
        mibViewProxy = ctx['mibViewProxy']
        if len(node) > 2:
            opt = node[2].attr
        else:
            opt = node[1].attr
        for c in opt:
            mibViewProxy.translateMassMode = 1            
            if c == 'd':
                mibViewProxy.translateFullDetails = 1
                mibViewProxy.translateMassMode = 0
            elif c == 'a':
                mibViewProxy.translateTrivial = 1
            elif c == 'l':
                mibViewProxy.translateLabeledOid = 1
            elif c == 'o':
                mibViewProxy.translateNumericOid = 1
            elif c == 's':
                mibViewProxy.translateSymbolicOid = 1
            else:
                raise error.PySnmpError('unsupported sub-option \"%s\"' % c)
            
def generator(cbCtx, ast):
    snmpEngine, ctx= cbCtx
    return __Generator().preorder((snmpEngine, ctx), ast)

class MibViewProxy(mibview.MibViewProxy):
    # MIB translate options
    translateFullDetails = 0
    translateTrivial = 0
    translateLabeledOid = 0
    translateNumericOid = 0
    translateSymbolicOid = 0

    # Implies SNMPWALK mode
    translateMassMode = 0
    
    # Override base class defaults
    buildEqualSign = 0

    _null = univ.Null()
    
    def getPrettyOidVal(self, mibViewController, oid, val):
        prefix, label, suffix = mibViewController.getNodeName(oid)
        modName, nodeDesc, _suffix = mibViewController.getNodeLocation(prefix)
        mibNode, = mibViewController.mibBuilder.importSymbols(
            modName, nodeDesc
        )        
        out = ''
        if self.translateFullDetails:
            if suffix:
                out = '%s::%s' % (modName, nodeDesc)
                out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ])
                out = out + '\n'
            else:
                out = out + '%s::%s\n%s ::= { %s }' % (
                    modName,
                    nodeDesc,
                    mibNode.asn1Print(),
                    ' '.join(
                        map(lambda x,y: '%s(%s)' % (y, x), prefix, label)
                        )
                    )
        elif self.translateTrivial:
            out = '%s ::= { %s %s' % (
                len(label) > 1 and label[-2] or ".", label[-1], prefix[-1]
            )
            if suffix:
                out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ])
            out = out + ' }'
        elif self.translateLabeledOid:
            out = '.' + '.'.join(
                map(lambda x,y: '%s(%s)' % (y, x),  prefix, label)
            )
            if suffix:
                out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ])
        elif self.translateNumericOid:
            out = '.' + '.'.join([ str(x) for x in prefix ])
            if suffix:
                out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ])
        elif self.translateSymbolicOid:
            out = '.' + '.'.join(label)
            if suffix:
                out = out + ' [ %s ]' % '.'.join([ str(x) for x in suffix ])
        if not out:
            out = mibview.MibViewProxy.getPrettyOidVal(
                self, mibViewController, oid, self._null
            )
        return out

snmpEngine = engine.SnmpEngine()

# Load up MIB texts (DESCRIPTION, etc.)
mibBuilder = snmpEngine.getMibBuilder()
mibBuilder.loadTexts = True

try:
    # Parse c/l into AST
    ast = Parser().parse(
        Scanner().tokenize(' '.join(sys.argv[1:]))
    )

    ctx = {}

    # Apply configuration to SNMP entity
    main.generator((snmpEngine, ctx), ast)
    ctx['mibViewProxy'] = MibViewProxy(ctx['mibViewController'])
    mibview.generator((snmpEngine, ctx), ast)
    pdu.readPduGenerator((snmpEngine, ctx), ast)
    generator((snmpEngine, ctx), ast)

except KeyboardInterrupt:
    sys.stderr.write('Shutting down...\n')

except error.PySnmpError:
    sys.stderr.write('Error: %s\n%s' % (sys.exc_info()[1], getUsage()))
    sys.exit(-1)

except Exception:
    sys.stderr.write('Process terminated: %s\n' % sys.exc_info()[1])
    for line in traceback.format_exception(*sys.exc_info()):
        sys.stderr.write(line.replace('\n', ';'))
    sys.exit(-1)

ctx['mibViewProxy'].buildValue = 0  # disable value printout

for oid, val in ctx['varBinds']:
    while 1:
        if val is None:
            val = univ.Null()
        sys.stdout.write('%s\n' % ctx['mibViewProxy'].getPrettyOidVal(
                ctx['mibViewController'], oid, val
            )
        )
        if not ctx['mibViewProxy'].translateMassMode:
            break
        try:
            oid, label, suffix = ctx['mibViewController'].getNextNodeName(oid)
        except NoSuchObjectError:
            break