PySMI: SNMP MIB Parser and Converter

1.6.3 · active · verified Sat Apr 11

PySMI is a pure-Python implementation of an SNMP SMI MIB parser and conversion library. It takes ASN.1 MIBs and can transform them into various formats, including JSON documents and PySNMP-compatible Python modules. It understands SMIv1, SMIv2, and common de-facto SMI dialects, and can automatically pull MIBs from local directories, ZIP archives, and HTTP servers. The current version is 1.6.3 and it actively supports Python 3.9+.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to compile an in-memory ASN.1 MIB module (`FOO-MIB`) into a JSON document using PySMI's `MibCompiler`. It sets up a `CallbackReader` to supply the MIB content and a `CallbackWriter` to print the resulting JSON to the console, illustrating the core transformation process.

import os
from pysmi.compiler import MibCompiler
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.json import JsonCodeGen
from pysmi.reader.callback import CallbackReader
from pysmi.writer.callback import CallbackWriter

# Example MIB content (simplified for demonstration)
mib_content = """
FOO-MIB DEFINITIONS ::= BEGIN
  IMPORTS
    MODULE-IDENTITY, OBJECT-TYPE, enterprises
      FROM SNMPv2-SMI;

  fooModule MODULE-IDENTITY
    LAST-UPDATED "202301010000Z"
    ORGANIZATION "Example Corp"
    CONTACT-INFO "support@example.com"
    DESCRIPTION
      "The MIB module for example devices."
    REVISION "202301010000Z"
    DESCRIPTION "Initial revision."
    ::= { enterprises 99999 }

  fooObjects OBJECT IDENTIFIER ::= { fooModule 1 }

  fooStatus OBJECT-TYPE
    SYNTAX INTEGER { up(1), down(2) }
    MAX-ACCESS read-only
    STATUS current
    DESCRIPTION
      "The operational status of a foo device."
    ::= { fooObjects 1 }

END
"""

def store_json_mib(mib_name, mib_data, *args):
    print(f"--- Compiled MIB: {mib_name} ---")
    print(mib_data)

# Initialize compiler infrastructure
mibCompiler = MibCompiler(
    SmiV2Parser(),
    JsonCodeGen(),
    CallbackWriter(store_json_mib)
)

# Add a reader that can provide our MIB content by name
mibCompiler.addSources(CallbackReader(lambda mibName, **kwargs: mib_content if mibName == 'FOO-MIB' else None))

# Compile the MIB
# Note: 'rebuild=True' forces compilation even if cached, 'genTexts=True' includes MIB descriptions
results = mibCompiler.compile('FOO-MIB', rebuild=True, genTexts=True)

print(f"Compilation results: {results}")

view raw JSON →