Compiling a SNMP MIB in VS Code to allow debugging

Hi all,

This is my first time using VS Code and any Toradex product so please bear with my ignorance. I’m using VS Code on a Windows 11 machine to build a Python program to act as an SNMP agent with a serial port output.

I was able to add the package python3-pysmi to the Dockerfile, and Dockerfile.debug files.

I was able to add pyserial and pysnmp to the requirements-*.txt files to load the appropriate python modules.

I’m trying to compile a custom MIB into a python module so it can be used to define my custom OIDs.

VS Code tells me I need to run the following command:
pysmi-compile --output-directory=/path/to/mibs MY-MIB.txt

When I run this command, I get an error
bash: pysmi-compile: command not found

When I add this command to my Dockerfiles and attempt a docker image compile, i also get an error.

47.43 Successfully installed pyasn1-0.6.1 pyserial-3.5 pysnmp-7.1.20 pysnmp-mibs-0.1.6
48.85 /bin/sh: 1: pysmi-compile: not found
------
Dockerfile:45
--------------------
  44 |     COPY requirements-release.txt /requirements-release.txt
  45 | >>> RUN . ${APP_ROOT}/.venv/bin/activate && \
  46 | >>>     pip3 install --upgrade pip && pip3 install -r requirements-release.txt && \
  47 | >>>     rm requirements-release.txt && \
  48 | >>>     pysmi-compile --output-directory ${APP_ROOT}/mib snmptoserial-mib.txt
  49 |     
--------------------
ERROR: failed to solve: process "/bin/sh -c . ${APP_ROOT}/.venv/bin/activate &&     pip3 install --upgrade pip && pip3 install -r requirements-release.txt &&     rm requirements-release.txt &&     pysmi-compile --output-directory ${APP_ROOT}/mib snmptoserial-mib.txt" did not complete successfully: exit code: 127

What am I doing wrong?

Thanks in advance for the help!

Software summary
------------------------------------------------------------
Bootloader:               U-Boot
Kernel version:           6.6.85-7.2.0-00045-gf1a07aac82ca #1-Torizon SMP PREEMPT Thu Feb 27 10:29:52 UTC 2025
Kernel command line:      root=LABEL=otaroot rootfstype=ext4 quiet logo.nologo vt.global_cursor_default=0 plymouth.ignore-serial-consoles splash fbcon=map:3 ostree=/ostree/boot.1/torizon/49c1e75c2944eb5ef277d5370041fb06faf8dd24a4cba412b756d8e7b946f87b/0
Distro name:              NAME="Torizon OS Upstream"
Distro version:           VERSION_ID=7.2.0-build.13
Distro variant:           VARIANT="Docker"
Hostname:                 colibri-imx7-emmc-12828052
------------------------------------------------------------

Hardware info
------------------------------------------------------------
HW model:                 Toradex Colibri iMX7D 1GB (eMMC) on Colibri Evaluation Board V3
Toradex version:          0039 V1.1B
Serial number:            12828052
Processor arch:           armv7l
------------------------------------------------------------

Hi, I’m the Toradex AI Assistant.

I might make mistakes. Our support team will step in if needed. If I answered your question, please tick the “Solution” checkbox. For follow-up questions to me, please use @ToradexAI in your post.

Did you like my answer? :+1: :-1:


Hello and welcome to the Toradex Community!

You’re encountering a common issue when trying to run the pysmi-compile tool: the error command not found occurs because the pysmi-compile command-line tool is not installed as a standalone executable by default. Instead, it’s typically accessed via Python module execution.

Solution Steps:

  1. Update Your Dockerfile
    Instead of calling pysmi-compile, use the Python module command.
    For example, replace your current RUN line with:

    RUN . ${APP_ROOT}/.venv/bin/activate && \
        pip3 install --upgrade pip && pip3 install -r requirements-release.txt && \
        pip3 install pysmi && \
        rm requirements-release.txt && \
        python3 -m pysmi compile --output-directory ${APP_ROOT}/mib snmptoserial-mib.txt
    

    This way, python3 -m pysmi compile ... correctly invokes the compiler in your virtual environment, even if there is no pysmi-compile binary available on the path.

  2. Ensure All Dependencies Are Included
    Add pysmi to both your requirements-release.txt and requirements-debug.txt files, so it’s available in both build and debug environments.

  3. General Advice for Local Development (on Windows)
    If you want to compile the MIB outside of the container for testing, create a virtual environment and install pysmi:

    python -m venv .venv --system-site-packages
    .venv\Scripts\activate
    pip install pysmi
    python -m pysmi compile --output-directory=[your_output_dir] [your_mib_file]
    

For more on Python in Torizon, see:

Let me know if you need step-by-step help configuring any of these files!

Best regards,
Toradex AI Assistant.

@ToradexAI

I have updated the Docker file with the corrections to use pysmi but I still get an error.

47.83 Installing collected packages: pyserial, ply, urllib3, pyasn1, MarkupSafe, idna, charset-normalizer, certifi, requests, pysnmp, Jinja2, pysnmp-mibs, pysmi
70.83 
70.85 Successfully installed Jinja2-3.1.6 MarkupSafe-3.0.2 certifi-2025.4.26 charset-normalizer-3.4.2 idna-3.10 ply-3.11 pyasn1-0.6.1 pyserial-3.5 pysmi-1.6.1 pysnmp-7.1.20 pysnmp-mibs-0.1.6 requests-2.32.3 urllib3-2.4.0
72.75 /serialtosnmp/.venv/bin/python3: No module named pysmi.__main__; 'pysmi' is a package and cannot be directly executed
------
Dockerfile:45
--------------------
  44 |     COPY requirements-release.txt /requirements-release.txt
  45 | >>> RUN . ${APP_ROOT}/.venv/bin/activate && \
  46 | >>>     pip3 install --upgrade pip && pip3 install -r requirements-release.txt && \
  47 | >>>     rm requirements-release.txt && \
  48 | >>>     python3 -m pysmi compile --output-directory ${APP_ROOT}/mib snmptoserial-mib.txt
  49 |     
--------------------
ERROR: failed to solve: process "/bin/sh -c . ${APP_ROOT}/.venv/bin/activate &&     pip3 install --upgrade pip && pip3 install -r requirements-release.txt &&     rm requirements-release.txt &&     python3 -m pysmi compile --output-directory ${APP_ROOT}/mib snmptoserial-mib.txt" did not complete successfully: exit code: 1

Initially, I think I was incorrectly defining the APP_ROOT in the Docker file. Current definition is as follows:
ARG APP_ROOT=/serialtosnmp

I have uploaded my Dockerfile if that helps.
Dockerfile (1.6 KB)

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Thank you for the update and the detailed information. You’re quite close! The error:

No module named pysmi.main; ‘pysmi’ is a package and cannot be directly executed

indicates that pysmi does not support being used with python -m pysmi. That’s why the module cannot be executed as a script entry point. The pysmi package does not implement a main.py file.

How to Compile Your MIB with pysmi:

Instead, you should use Python code to invoke the compiler directly, for example via a short script, or by using a one-liner in your Dockerfile as shown below.

Recommended Solution:

  1. Create a short Python script to compile the MIB.

Create a file called compile_mib.py with these contents:

from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.callback import CallbackWriter
from pysmi.parser.smi import parserFactory
from pysmi.codegen.pysnmp import PySnmpCodeGen
from pysmi.borrower.pyfile import PyFileBorrower
from pysmi.searcher.stub import StubSearcher
from pysmi import debug

# Edit these as appropriate
input_mib = 'snmptoserial-mib.txt'
output_dir = '/serialtosnmp/mib'

compiler = MibCompiler(
    PySnmpCodeGen(),
    FileReader('.'),
    CallbackWriter(lambda mibname, contents: open(f"{output_dir}/{mibname}.py", "w").write(contents))
)

compiler.addSources(FileReader('.'))
compiler.addSearchers(StubSearcher('SNMPv2-SMI', 'SNMPv2-TC', 'SNMPv2-CONF'))
compiler.compile(input_mib)

Alternatively, for a single-run command:

If you want to keep it inline in the Dockerfile, replace your build step with a small Python one-liner:

RUN . ${APP_ROOT}/.venv/bin/activate && \
  python3 -c "from pysmi.compiler import compile; compile('snmptoserial-mib.txt', outputDirectory='${APP_ROOT}/mib')"
  • Make sure your snmptoserial-mib.txt file is also copied into the container before this step.

Dockerfile Example:

FROM --platform=linux/arm/v7 torizon/debian:3-bookworm

ARG APP_ROOT=/serialtosnmp
WORKDIR ${APP_ROOT}

RUN apt-get update && \
    apt-get install -y --no-install-recommends python3 python3-pip python3-venv && \
    apt-get clean && \
    apt-get autoremove && \
    rm -rf /var/lib/apt/lists/*

COPY requirements-release.txt .
RUN python3 -m venv .venv && \
    . .venv/bin/activate && \
    pip3 install --upgrade pip && \
    pip3 install -r requirements-release.txt && \
    rm requirements-release.txt

COPY snmptoserial-mib.txt .
RUN . .venv/bin/activate && \
    python3 -c "from pysmi.compiler import compile; compile('snmptoserial-mib.txt', outputDirectory='${APP_ROOT}/mib')"

References:

Let me know if you need the content of compile_mib.py as a file, or have further issues!

Best regards,
Toradex AI Assistant.

@ToradexAI

I should have mentioned this earlier. I am trying to implement SNMPv3 agent. Are the examples given appropriate for SNMPv3?

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Hello again!

Yes, the MIB compilation steps and the approach described are fully appropriate for use with an SNMPv3 agent. MIB compilation defines your managed objects (OIDs) in a way your Python SNMP agent code can use—this process is independent of whether you use SNMPv1, v2c, or v3. The SNMP version (including SNMPv3’s authentication and privacy features) is handled in your agent’s implementation logic, not in the MIB compilation process.

After compiling your MIB into a Python module, you can proceed to implement your SNMPv3 agent with the desired security configuration.

You can refer to the following example structure for implementing an SNMPv3 agent using pysnmp, including robust security settings:

from pysnmp.hlapi import *
from pysnmp.smi import builder, view, compiler, rfc1902
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context

# Create SNMP engine instance with unique engine ID
snmpEngine = engine.SnmpEngine()

# Add USM user with security levels
config.addV3User(
    snmpEngine,
    userName='youruser',
    authProtocol=usmHMACSHAAuthProtocol,
    authKey='authkey123',
    privProtocol=usmAesCfb128Protocol,
    privKey='privkey123'
)

# Setup transport endpoint
config.addSocketTransport(
    snmpEngine,
    udp.domainName,
    udp.UdpTransport().openServerMode(('0.0.0.0', 161))
)

Security Best Practices for SNMPv3:

  • Use ‘authPriv’ (authentication and privacy enabled).
  • Prefer SHA (or stronger) as the authentication protocol.
  • Prefer AES for privacy protocol.
  • Store credentials securely.

References:

If you’d like a full end-to-end agent code example integrating your serial port, let me know!

Best regards,
Toradex AI Assistant.

@ToradexAI

I created compile_mib.py as suggested, and ran in in the terminal.

It did not compile and I got the following error.

(.venv) 🐧 SAbrahamian @MU69-PC~/snmptoserial: /home/SAbrahamian/snmptoserial/.venv/bin/python3 /home/SAbrahamian/snmptoserial/src/compile_mib.py
Traceback (most recent call last):
  File "/home/SAbrahamian/snmptoserial/src/compile_mib.py", line 24, in <module>
    compiler.compile(input_mib)
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/compiler.py", line 253, in compile
    for mibTree in self._parser.parse(fileData):
                   ^^^^^^^^^^^^^^^^^^
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/codegen/base.py", line 350, in __getattr__
    raise AttributeError(
AttributeError: 'PySnmpCodeGen' object has no attribute 'parse'

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Hello,

Thank you for providing the error details. This issue appears because the MIB compiler object was not initialized correctly—the parser component is missing from the initialization. To resolve this, please use the following revised example for your compile_mib.py script:

from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiStarParser
from pysmi.codegen.pysnmp import PySnmpCodeGen

# Paths (adjust as needed)
input_mib = 'snmptoserial-mib.txt'
output_dir = '/serialtosnmp/mib'  # Make sure this directory exists

# Initialize components
parser = SmiStarParser()
codegen = PySnmpCodeGen()
reader = FileReader('.')
writer = PyFileWriter(output_dir)

# Initialize MIB compiler with parser and other components
mibCompiler = MibCompiler(
    parser,
    codegen,
    reader,
    writer
)

results = mibCompiler.compile(input_mib)
print(results)

Important notes:

  • Make sure the output directory (e.g., /serialtosnmp/mib or a local directory like ./mib) exists, or create it before running the script.
  • Adjust the input and output paths based on your file locations.

This script will correctly compile your MIB file into the output directory as a Python module suitable for use with pysnmp (including for SNMPv3 agents).

References:

Please let me know if this resolves the error or if you need additional help.

Best regards,
Toradex AI Assistant.

@ToradexAI

I changed my compile_mib.py to the following:

from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen

# This is a standalone script to compile MIB files using PySMI

# File locations for MIB files
input_dir = '/home/SAbrahamian/snmptoserial/mib'
output_dir = '/home/SAbrahamian/snmptoserial/mib'
input_mib = 'snmptoserial_mib.txt'

mibCompiler = MibCompiler(
    SmiV2Parser(),                # parser (not instantiated with a file)
    PySnmpCodeGen(),              # code generator
    PyFileWriter(output_dir)      # writer
)
mibCompiler.add_sources(FileReader(input_dir))  # add input directory

results = mibCompiler.compile(input_mib)
print(results)

When I run it, I get the following message:

(.venv) 🐧 SAbrahamian @MU69-PC~/snmptoserial: /home/SAbrahamian/snmptoserial/.venv/bin/python3 /home/SAbrahamian/snmptoserial/src/compile_mib.py
{'snmptoserial_mib.txt': 'failed'}

What am I missing?

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Hello again!

You are very close—the script logic is correct, but when you see results like:

{'snmptoserial_mib.txt': 'failed'}

that means the MIB file did not compile successfully. To solve this, let’s enable debugging and check some common issues.


1. Enable Debug Output

Add these lines to your script before creating the compiler to see what went wrong:

from pysmi import debug
debug.setLogger(debug.Debug('all'))

This will print detailed errors. Rerun the script and review the output for any specific parsing or dependency errors.


2. Common Issues Checklist

  • File Name and Path: Double-check that snmptoserial_mib.txt is in /home/SAbrahamian/snmptoserial/mib.
    • Use os.listdir(input_dir) in your script to verify it’s there.
  • Syntax: Make sure your MIB file is valid and contains correct ASN.1 syntax for your MIB type (SmiV2 if using SmiV2Parser()).
  • Dependencies: If your MIB imports from other standard MIBs (like SNMPv2-SMI or SNMPv2-TC), make sure these can be found. You can add borrowed sources pointing to where those compiled MIBs live.
  • File Permissions: Ensure the user running the script can read the input and write to the output directory.

3. Example with Debugging

Here’s your improved script including debug and verification:

from pysmi import debug
import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen

debug.setLogger(debug.Debug('all'))

input_dir = '/home/SAbrahamian/snmptoserial/mib'
output_dir = '/home/SAbrahamian/snmptoserial/mib'
input_mib = 'snmptoserial_mib.txt'

print("Files in input directory:", os.listdir(input_dir))

mibCompiler = MibCompiler(
    SmiV2Parser(),
    PySnmpCodeGen(),
    PyFileWriter(output_dir)
)
mibCompiler.addSources(FileReader(input_dir))

results = mibCompiler.compile(input_mib)
print(results)

4. If Errors Reference Missing Dependencies

If you see errors about missing imported MIBs (like SNMPv2-SMI), you could add code to borrow them:

# after creating mibCompiler
from pysmi.borrower.pyfile import PyFileBorrower
mibCompiler.addBorrowers(PyFileBorrower(input_dir))

Or, point to the PySNMP provided MIBs path if needed.


References


After you run with debug mode on, share the first error message you see if you need help interpreting it!

Best regards,
Toradex AI Assistant.

@ToradexAI

I have updated my compile_mib.py to the following:

from pysmi import debug
import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen

debug.set_logger(debug.Debug('all'))

# This is a standalone script to compile MIB files using PySMI

# File locations for MIB files
input_dir = '/home/SAbrahamian/snmptoserial/mib'
output_dir = '/home/SAbrahamian/snmptoserial/mib'
input_mib = 'snmptoserialmib.txt'

print("Files in input directory:", os.listdir(input_dir))

mibCompiler = MibCompiler(
    SmiV2Parser(),                # parser (not instantiated with a file)
    PySnmpCodeGen(),              # code generator
    PyFileWriter(output_dir)      # writer
)
mibCompiler.add_sources(FileReader(input_dir))  # add input directory

results = mibCompiler.compile(input_mib)
print(results)

This is the error recieved.

(.venv) 🐧 SAbrahamian @MU69-PC~/snmptoserial: /home/SAbrahamian/snmptoserial/.venv/bin/python3 /home/SAbrahamian/snmptoserial/src/compile_mib.py
2025-05-16 14:17:24,962 pysmi: running pysmi version 1.6.1
2025-05-16 14:17:24,962 pysmi: debug category 'all' enabled
Files in input directory: ['snmptoserialmib.txt']
Traceback (most recent call last):
  File "/home/SAbrahamian/snmptoserial/src/compile_mib.py", line 21, in <module>
    SmiV2Parser(),                # parser (not instantiated with a file)
    ^^^^^^^^^^^^^
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/parser/smi.py", line 34, in __init__
    self.lexer = self.defaultLexer(tempdir=tempdir)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/lexer/smi.py", line 182, in __init__
    self.reset()
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/lexer/smi.py", line 191, in reset
    logger = debug.logger.getCurrentLogger()
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Debug' object has no attribute 'getCurrentLogger'. Did you mean: 'get_current_logger'?

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Thank you for providing the traceback. This error:

AttributeError: 'Debug' object has no attribute 'getCurrentLogger'. Did you mean: 'get_current_logger'?

means that the method in your version of PySMI is now called get_current_logger instead of getCurrentLogger. This is likely due to changes for compatibility with newer Python versions.

Solution

Update the debug enabling line in your script to use the new naming convention:

Replace:

debug.set_logger(debug.Debug('all'))

with:

debug.setLogger(debug.Debug('all'))

or, if your pysmi is still not working, try:

debug.set_logger(debug.Debug('all'))  # For older pysmi versions

But the capital “L” version should work:

So update that one line in your script:

debug.setLogger(debug.Debug('all'))

Full Working Example

Here’s the fixed version for your script:

from pysmi import debug
import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen

debug.setLogger(debug.Debug('all'))  # use setLogger with a capital L

input_dir = '/home/SAbrahamian/snmptoserial/mib'
output_dir = '/home/SAbrahamian/snmptoserial/mib'
input_mib = 'snmptoserialmib.txt'

print("Files in input directory:", os.listdir(input_dir))

mibCompiler = MibCompiler(
    SmiV2Parser(),
    PySnmpCodeGen(),
    FileReader(input_dir),
    PyFileWriter(output_dir)
)

results = mibCompiler.compile(input_mib)
print(results)

References


This change should resolve the AttributeError and allow PySMI to log debug output, so you can proceed to troubleshoot any MIB compilation errors.

Best regards,
Toradex AI Assistant.

@ToradexAI

I am using PySMI version 1.6.1

The attribute error with getCurrentLogger references a file directly within the site-packages directory for python3. How can this be resolved without modifying the python packages themselves?

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Since we want to avoid modifying the Python packages, let's try a different approach that doesn't rely on the debug functionality. Here's a modified version of the script that should work with PySMI 1.6.1:

import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen
from pysmi.borrower.pyfile import PyFileBorrower
from pysmi.searcher.stub import StubSearcher

File locations for MIB files

input_dir = ‘/home/SAbrahamian/snmptoserial/mib’
output_dir = ‘/home/SAbrahamian/snmptoserial/mib’
input_mib = ‘snmptoserialmib.txt’

print(“Files in input directory:”, os.listdir(input_dir))

Initialize the compiler with all necessary components

mibCompiler = MibCompiler(
SmiV2Parser(),
PySnmpCodeGen(),
FileReader(input_dir),
PyFileWriter(output_dir)
)

Add searchers for common SNMP MIBs

mibCompiler.addSearchers(StubSearcher(*PySnmpCodeGen.baseMibs))

Try to compile

try:
results = mibCompiler.compile(input_mib)
if results:
print(“\nCompilation results:”)
for mib, result in results.items():
print(f"{mib}: {result}“)
except Exception as e:
print(f”\nError during compilation: {str(e)}")

  • This version:
    • Removes the problematic debug functionality
    • Adds error handling to better understand any issues
    • Includes searchers for base MIBs that your custom MIB might depend on
    • Provides more detailed output about the compilation process

If you still get compilation errors, they should now be more descriptive about what's going wrong. Could you run this version and share any errors you see?

Best regards,
Toradex AI Assistant.

@ToradexAI

I’ve updated my compile_mib.py to this:

from pysmi import debug
import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen
from pysmi.searcher import StubSearcher

debug.set_logger(debug.Debug('all'))

# This is a standalone script to compile MIB files using PySMI

# File locations for MIB files
input_dir = '/home/SAbrahamian/snmptoserial/mib'
output_dir = '/home/SAbrahamian/snmptoserial/mib'
input_mib = 'snmptoserialmib.txt'

print("Files in input directory:", os.listdir(input_dir))

parser = SmiV2Parser()  # Parser for MIB files
codegen = PySnmpCodeGen()  # Code generator for PySNMP
writer = PyFileWriter(output_dir)  # Writer to output directory

mibCompiler = MibCompiler(
    parser,
    codegen,
    writer
)
mibCompiler.add_sources(FileReader(input_dir))  # add input directory
mibCompiler.add_searchers(StubSearcher(*PySnmpCodeGen.baseMibs))

#results = mibCompiler.compile(input_mib)
#print(results)

try:
    results = mibCompiler.compile(input_mib)
    if results:
        print("\nCompilation results:")

    for mib, result in results.items():
        print(f"{mib}: {result}")

except Exception as e:
    print(f"\nError during compilation: {str(e)}")

I’m still getting errors:

(.venv) 🐧 SAbrahamian @MU69-PC~/snmptoserial: /home/SAbrahamian/snmptoserial/.venv/bin/python3 /home/SAbrahamian/snmptoserial/src/compile_mib.py
2025-05-16 15:31:01,155 pysmi: running pysmi version 1.6.1
2025-05-16 15:31:01,156 pysmi: debug category 'all' enabled
Files in input directory: ['snmptoserialmib.txt']
Traceback (most recent call last):
  File "/home/SAbrahamian/snmptoserial/src/compile_mib.py", line 21, in <module>
    parser = SmiV2Parser()  # Parser for MIB files
             ^^^^^^^^^^^^^
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/parser/smi.py", line 34, in __init__
    self.lexer = self.defaultLexer(tempdir=tempdir)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/lexer/smi.py", line 182, in __init__
    self.reset()
  File "/home/SAbrahamian/snmptoserial/.venv/lib/python3.11/site-packages/pysmi/lexer/smi.py", line 191, in reset
    logger = debug.logger.getCurrentLogger()
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Debug' object has no attribute 'getCurrentLogger'. Did you mean: 'get_current_logger'?

What am I missing?

Thanks for your response.

Please remember to tick the “Solution” checkbox below if my response solves your question. If you have follow-up questions, just continue to tag me using @ToradexAI in your new posts.

Did you like my answer? :+1: :-1:


Thank you for providing the exact traceback. The root cause is a compatibility issue between PySMI 1.6.1 and Python 3.11+: the PySMI debug code uses camelCase method names (e.g., getCurrentLogger()) while recent Python standards and PySMI’s newer code expect snake_case (e.g., get_current_logger()).

However, you don’t need debug logging to successfully compile your MIB.
The best and safest way forward is to completely remove the debug functionality from your script. This avoids having to patch site-packages or downgrade Python.


Working Script Without Debug

Here’s a clean version to use:

import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen
from pysmi.searcher.stub import StubSearcher

input_dir = '/home/SAbrahamian/snmptoserial/mib'
output_dir = '/home/SAbrahamian/snmptoserial/mib'
input_mib = 'snmptoserialmib.txt'

print("Files in input directory:", os.listdir(input_dir))

# Initialize components
parser = SmiV2Parser()
codegen = PySnmpCodeGen()
reader = FileReader(input_dir)
writer = PyFileWriter(output_dir)

mibCompiler = MibCompiler(
    parser,
    codegen,
    reader,
    writer
)

# Add searchers for common SNMP MIBs
mibCompiler.addSearchers(StubSearcher(*PySnmpCodeGen.baseMibs))

try:
    results = mibCompiler.compile(input_mib)
    if results:
        print("\nCompilation results:")
        for mib, result in results.items():
            print(f"{mib}: {result}")
except Exception as e:
    print(f"\nError during compilation: {str(e)}")

  • This script does NOT use any debug functions.
  • It will fail gracefully and show you the precise import/syntax error if the MIB cannot be compiled.
  • If there are errors in your MIB file, they will now be clearly shown in your terminal output.

References:


Try this version and let me know the compilation output! If you receive an error regarding the MIB content itself, please share the error message for further guidance.

Best regards,
Toradex AI Assistant.

Was able to get it working. Here is the updated code:

import os
from pysmi.compiler import MibCompiler
from pysmi.reader.localfile import FileReader
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.smi import SmiV2Parser
from pysmi.codegen.pysnmp import PySnmpCodeGen
from pysmi.searcher import StubSearcher
from pysmi.searcher import PyPackageSearcher

# This is a standalone script to compile MIB files using PySMI

# File locations for MIB files
input_dir = '/path/to/your/mib/'
output_dir = '/path/to/your/mib/'
input_mib = 'your_mib.txt'

print("Files in input directory:", os.listdir(input_dir))

parser = SmiV2Parser()  # Parser for MIB files
codegen = PySnmpCodeGen()  # Code generator for PySNMP
writer = PyFileWriter(output_dir)  # Writer to output directory


mibCompiler = MibCompiler(
    parser,
    codegen,
    writer
)
mibCompiler.add_sources(FileReader(input_dir))  # add input directory
mibCompiler.add_searchers(StubSearcher(*PySnmpCodeGen.baseMibs))
mibCompiler.add_searchers(PyPackageSearcher('pysnmp.smi.mibs'))  # add PySNMP MIBs

try:
    results = mibCompiler.compile(input_mib)
    if results:
        print("\nCompilation results:")

    for mib, result in results.items():
        print(f"{mib}: {result}")

except Exception as e:
    print(f"\nError during compilation: {str(e)}")

The proper syntax for the MIB file must be adhered to, otherwise errors will occur.

Hey @SAbrahamian,

Glad you got this working, our team doesn’t have much experience with this, so thank you for posting the final solution you found.

-Eric