!pip3 install pysmi

"""
Explanation: Parsing SNMP MIBs with PySMI
End of explanation
"""


from pysmi.reader import FileReader, HttpReader

reader = FileReader('/tmp/SNMP-MIBs', recursive=True, ignoreErrors=True)

"""
Explanation: Reader
We are creating a Readers for local MIB files.
End of explanation
"""


from pysmi.parser.dialect import smiV1Relaxed
from pysmi.parser.smi import parserFactory

Parser = parserFactory(**smiV1Relaxed)
parser = Parser()

"""
Explanation: Parser
There are different Parsers for (strict) SMIv1 and SMIv2 and one that accepts "relaxed" syntax. Given that few SNMP MIBs are syntactically correct, a "relaxed" parser is instantiated.
End of explanation
"""


from pysmi.parser import SmiStarParser
parser = SmiStarParser()

"""
Explanation: The SmiStarParser() is a convenient short-cut for the same thing.
End of explanation
"""


from pysmi.codegen import JsonCodeGen
codegen = JsonCodeGen()

"""
Explanation: Code Generator
The are Code Generators for JSON and PySNMP-style MIBs.
End of explanation
"""


from pysmi.writer import CallbackWriter

def callback(mibname, doc, context):
    with open('/tmp/SNMP-MIBs-JSON/{}.json'.format(mibname), 'wt') as fp:
        fp.write(doc)
    
writer = CallbackWriter(callback)

"""
Explanation: Writer
The Writer gets the output from the Generator. The FileWriter(path) can be used to save the output to a file inside of path. Alternatively the CallbackWriter() can be used for further processing of the output. The code below shows how it works although in this example it operates similar to the FileWriter().
End of explanation
"""


from pysmi.compiler import MibCompiler

compiler = MibCompiler(parser, codegen, writer)

"""
Explanation: Compiler
The Compiler ties the Parser, Code Generator and Writer together.
End of explanation
"""


compiler.addSources(reader)

"""
Explanation: The reader is added as source to the Compiler.
End of explanation
"""


status = compiler.compile('IF-MIB', 'VRRP-MIB')

"""
Explanation: Finally the Compiler can be "run" against some MIB names(!).
End of explanation
"""


status

"""
Explanation: The status shows that the imported MIBs were also compiled.
End of explanation
"""


!ls /tmp/SNMP-MIBs-JSON

!head /tmp/SNMP-MIBs-JSON/IF-MIB.json

"""
Explanation: The Writer created the JSON files.
End of explanation
"""


status = compiler.compile('MISSING-MIB')
status

"""
Explanation: The status will also show if a MIB could not be processed.
End of explanation
"""


