Beispiel #1
0
    def __init__(self, mib_list, src_dir_list, http_sources=None):
        if "BFT_DEBUG" in os.environ:
            self.dbg = os.environ.get('BFT_DEBUG')
        else:
            self.dbg = ""

        if "yy" in self.dbg:
            # VERY verbose, but essential for spotting
            # possible  ASN.1 errors
            from pysmi import debug
            debug.setLogger(debug.Debug('reader', 'compiler'))

        # Initialize compiler infrastructure
        mibCompiler = MibCompiler(SmiStarParser(), JsonCodeGen(),
                                  CallbackWriter(self.callback_func))

        # search for source MIBs here
        mibCompiler.addSources(*[FileReader(x) for x in src_dir_list])

        if http_sources:
            # search for source MIBs at Web sites
            mibCompiler.addSources(*[HttpReader(*x) for x in http_sources])

        # never recompile MIBs with MACROs
        mibCompiler.addSearchers(StubSearcher(*JsonCodeGen.baseMibs))

        # run recursive MIB compilation
        mibCompiler.compile(*mib_list)
    def fetch_mib(mib):
        target_directory = os.path.dirname(pysnmp_mibs.__file__)

        reader = HttpReader('mibs.snmplabs.com', 80, '/asn1/@mib@')
        mibCompiler = MibCompiler(SmiStarParser(), PySnmpCodeGen(),
                                  PyFileWriter(target_directory))

        mibCompiler.addSources(reader)

        mibCompiler.compile(mib)
def _compile_cloudify_mib():
    mibs_dir = "pysnmp_mibs"
    if os.path.exists('{0}/{1}.py'.format(mibs_dir, CLOUDIFY_MIB)):
        return
    mib_compiler = MibCompiler(SmiV2Parser(), PySnmpCodeGen(),
                               PyFileWriter(mibs_dir))
    cloudify_mib_dir = os.path.dirname(os.path.realpath(__file__))
    mib_compiler.addSources(FileReader(cloudify_mib_dir))
    mib_compiler.addSources(HttpReader('mibs.snmplabs.com', 80, '/asn1/@mib@'))
    mib_compiler.addSearchers(PyFileSearcher(mibs_dir))
    mib_compiler.compile(CLOUDIFY_MIB)
Beispiel #4
0
def _compile_mib_to_json(mib, source_mib_directories, destination_directory):
    from pysmi.codegen import JsonCodeGen
    from pysmi.compiler import MibCompiler
    from pysmi.parser import SmiV1CompatParser
    from pysmi.reader import FileReader, HttpReader
    from pysmi.searcher import AnyFileSearcher, StubSearcher
    from pysmi.writer import FileWriter

    mib_stubs = JsonCodeGen.baseMibs

    compile_documentation = True

    # Compiler infrastructure
    searchers = [
        AnyFileSearcher(destination_directory).setOptions(exts=['.json']),
        StubSearcher(*mib_stubs)
    ]

    code_generator = JsonCodeGen()

    file_writer = FileWriter(destination_directory).setOptions(suffix='.json')

    mib_compiler = MibCompiler(SmiV1CompatParser(tempdir=''), code_generator,
                               file_writer)

    # use source_mib_directories as mibs source
    for source_directory in source_mib_directories:
        mib_compiler.addSources(FileReader(source_directory))
    # use snmp mibs repo as mibs source
    reader = HttpReader('raw.githubusercontent.com', 80,
                        '/projx/snmp-mibs/master/@mib@')
    mib_compiler.addSources(reader)

    mib_compiler.addSearchers(*searchers)

    processed = mib_compiler.compile(
        mib,
        **dict(
            noDeps=False,
            rebuild=False,
            dryRun=False,
            dstTemplate=None,
            genTexts=compile_documentation,
            textFilter=False and (lambda symbol, text: text) or None,
            writeMibs=True,
            ignoreErrors=False,
        ))

    return processed
Beispiel #5
0
def fetch_mib(mib):
    import pysnmp_mibs
    from pysmi.codegen import PySnmpCodeGen
    from pysmi.compiler import MibCompiler
    from pysmi.parser import SmiStarParser
    from pysmi.reader import HttpReader
    from pysmi.writer import PyFileWriter

    target_directory = os.path.dirname(pysnmp_mibs.__file__)

    reader = HttpReader('mibs.snmplabs.com', 80, '/asn1/@mib@')
    mibCompiler = MibCompiler(SmiStarParser(), PySnmpCodeGen(), PyFileWriter(target_directory))

    mibCompiler.addSources(reader)

    mibCompiler.compile(mib)
Beispiel #6
0
    def __init__(self, mib_list, src_dir_list, http_sources=None):
        if "BFT_DEBUG" in os.environ:
            self.dbg = os.environ.get('BFT_DEBUG')
        else:
            self.dbg = ""

        if "yy" in self.dbg:
            # VERY verbose, but essential for spotting
            # possible  ASN.1 errors
            from pysmi import debug
            debug.setLogger(debug.Debug('reader', 'compiler'))

        # Initialize compiler infrastructure
        mibCompiler = MibCompiler(SmiStarParser(), JsonCodeGen(),
                                  CallbackWriter(self.callback_func))

        # search for source MIBs here
        mibCompiler.addSources(*[FileReader(x) for x in src_dir_list])

        if http_sources:
            # search for source MIBs at Web sites
            mibCompiler.addSources(*[HttpReader(*x) for x in http_sources])

        # never recompile MIBs with MACROs
        mibCompiler.addSearchers(StubSearcher(*JsonCodeGen.baseMibs))

        # run recursive MIB compilation
        mib_dict = mibCompiler.compile(*mib_list)

        err = False

        if mib_dict is None or mib_dict == {}:
            print(
                "ERROR: failed on mib compilation (mibCompiler.compile returned an empty dictionary)"
            )
            err = True

        for key, value in mib_dict.iteritems():
            if value == 'unprocessed':
                print("ERROR: failed on mib compilation: " + key + ": " +
                      value)
                err = True

        if err:
            raise Exception("SnmpMibs failed to initialize.")
        elif 'BFT_DEBUG' in os.environ:
            print('# %d MIB modules compiled' % len(mib_dict))
Beispiel #7
0
def fetch_mib(mib, source_url):
    try:
        from urllib.parse import urlparse
    except ImportError:
        from urlparse import urlparse

    import pysnmp_mibs
    from pysmi.codegen import PySnmpCodeGen
    from pysmi.compiler import MibCompiler
    from pysmi.parser import SmiStarParser
    from pysmi.reader import HttpReader
    from pysmi.writer import PyFileWriter

    target_directory = os.path.dirname(pysnmp_mibs.__file__)

    parsed_url = urlparse(source_url)
    reader = HttpReader(parsed_url.netloc, 80, parsed_url.path)
    mibCompiler = MibCompiler(SmiStarParser(), PySnmpCodeGen(),
                              PyFileWriter(target_directory))

    mibCompiler.addSources(reader)

    mibCompiler.compile(mib)
from pysmi.reader import HttpReader
from pysmi.searcher import StubSearcher
from pysmi.writer import CallbackWriter
from pysmi.parser import SmiStarParser
from pysmi.codegen import JsonCodeGen
from pysmi.compiler import MibCompiler

inputMibs = ['IF-MIB', 'IP-MIB']

httpSources = [('mibs.snmplabs.com', 80, '/asn1/@mib@')]


# store compiled MIBs by calling this function
def store_mibs(mibName, jsonDoc, cbCtx):
    print('# MIB module %s' % mibName)
    print(jsonDoc)


mibCompiler = MibCompiler(SmiStarParser(), JsonCodeGen(),
                          CallbackWriter(store_mibs))

# pull ASN.1 MIBs over HTTP
mibCompiler.addSources(*[HttpReader(*x) for x in httpSources])

# never recompile MIBs with ASN.1 MACROs
mibCompiler.addSearchers(StubSearcher(*JsonCodeGen.baseMibs))

status = mibCompiler.compile(*inputMibs)

print(status)
Beispiel #9
0
from pysmi.borrower import PyFileBorrower
from pysmi.writer import PyFileWriter
from pysmi.parser import NullParser
from pysmi.codegen import NullCodeGen
from pysmi.compiler import MibCompiler
# from pysmi import debug

# debug.setLogger(debug.Debug('compiler'))

inputMibs = ['BORROWED-MIB']

httpBorrowers = [('mibs.snmplabs.com', 80, '/pysnmp/notexts/@mib@')]
dstDirectory = '.pysnmp-mibs'

# Initialize compiler infrastructure

mibCompiler = MibCompiler(NullParser(), NullCodeGen(),
                          PyFileWriter(dstDirectory))

# check compiled/borrowed MIBs in our own productions
mibCompiler.addSearchers(PyFileSearcher(dstDirectory))

# search for precompiled MIBs at Web sites
mibCompiler.addBorrowers(
    *[PyFileBorrower(HttpReader(*x)) for x in httpBorrowers])

# run MIB compilation
results = mibCompiler.compile(*inputMibs)

print('Results: %s' % ', '.join(['%s:%s' % (x, results[x]) for x in results]))
Beispiel #10
0
# from pysmi import debug

# debug.setLogger(debug.Debug('borrower', 'reader', 'searcher'))

inputMibs = ['BORROWED-MIB']
httpSources = [('mibs.snmplabs.com', 80, '/asn1/@mib@')]
httpBorrowers = [('mibs.snmplabs.com', 80, '/pysnmp/notexts/@mib@')]
dstDirectory = '.pysnmp-mibs'

# Initialize compiler infrastructure

mibCompiler = MibCompiler(SmiStarParser(), PySnmpCodeGen(),
                          PyFileWriter(dstDirectory))

# search for source MIBs at Web sites
mibCompiler.addSources(*[HttpReader(*x) for x in httpSources])

# never recompile MIBs with MACROs
mibCompiler.addSearchers(StubSearcher(*PySnmpCodeGen.baseMibs))

# check compiled/borrowed MIBs in our own productions
mibCompiler.addSearchers(PyFileSearcher(dstDirectory))

# search for compiled MIBs at Web sites if source is not available or broken
mibCompiler.addBorrowers(*[
    PyFileBorrower(HttpReader(*x)).setOptions(genTexts=False)
    for x in httpBorrowers
])

# run non-recursive MIB compilation
results = mibCompiler.compile(*inputMibs)
Beispiel #11
0
    def __init__(self, host, port, raw_mibs, compiled_mibs):

        self.oid_mapping = {}
        self.databus_mediator = DatabusMediator(self.oid_mapping)
        # mapping between OID and databus keys

        # Create SNMP engine
        self.snmpEngine = engine.SnmpEngine()

        # Configure SNMP compiler
        mib_builder = self.snmpEngine.getMibBuilder()
        addMibCompiler(mib_builder, destination=compiled_mibs)
        mib_builder.getMibCompiler().addSources(FileReader(raw_mibs))
        mib_builder.getMibCompiler().addSources(
            HttpReader("mibs.snmplabs.com", 80, "/asn1/@mib@"))

        # Transport setup
        udp_sock = gevent.socket.socket(gevent.socket.AF_INET,
                                        gevent.socket.SOCK_DGRAM)
        udp_sock.setsockopt(gevent.socket.SOL_SOCKET,
                            gevent.socket.SO_BROADCAST, 1)
        udp_sock.bind((host, port))
        self.server_port = udp_sock.getsockname()[1]
        # UDP over IPv4
        self.addSocketTransport(self.snmpEngine, udp.domainName, udp_sock)

        # SNMPv1
        config.addV1System(self.snmpEngine, "public-read", "public")

        # SNMPv3/USM setup
        # user: usr-md5-des, auth: MD5, priv DES
        config.addV3User(
            self.snmpEngine,
            "usr-md5-des",
            config.usmHMACMD5AuthProtocol,
            "authkey1",
            config.usmDESPrivProtocol,
            "privkey1",
        )
        # user: usr-sha-none, auth: SHA, priv NONE
        config.addV3User(self.snmpEngine, "usr-sha-none",
                         config.usmHMACSHAAuthProtocol, "authkey1")
        # user: usr-sha-aes128, auth: SHA, priv AES/128
        config.addV3User(
            self.snmpEngine,
            "usr-sha-aes128",
            config.usmHMACSHAAuthProtocol,
            "authkey1",
            config.usmAesCfb128Protocol,
            "privkey1",
        )

        # Allow full MIB access for each user at VACM
        config.addVacmUser(
            self.snmpEngine,
            1,
            "public-read",
            "noAuthNoPriv",
            readSubTree=(1, 3, 6, 1, 2, 1),
            writeSubTree=(1, 3, 6, 1, 2, 1),
        )
        config.addVacmUser(
            self.snmpEngine,
            2,
            "public-read",
            "noAuthNoPriv",
            readSubTree=(1, 3, 6, 1, 2, 1),
            writeSubTree=(1, 3, 6, 1, 2, 1),
        )
        config.addVacmUser(
            self.snmpEngine,
            3,
            "usr-md5-des",
            "authPriv",
            readSubTree=(1, 3, 6, 1, 2, 1),
            writeSubTree=(1, 3, 6, 1, 2, 1),
        )
        config.addVacmUser(
            self.snmpEngine,
            3,
            "usr-sha-none",
            "authNoPriv",
            readSubTree=(1, 3, 6, 1, 2, 1),
            writeSubTree=(1, 3, 6, 1, 2, 1),
        )
        config.addVacmUser(
            self.snmpEngine,
            3,
            "usr-sha-aes128",
            "authPriv",
            readSubTree=(1, 3, 6, 1, 2, 1),
            writeSubTree=(1, 3, 6, 1, 2, 1),
        )

        # Get default SNMP context this SNMP engine serves
        snmpContext = context.SnmpContext(self.snmpEngine)

        # Register SNMP Applications at the SNMP engine for particular SNMP context
        self.resp_app_get = conpot_cmdrsp.c_GetCommandResponder(
            self.snmpEngine, snmpContext, self.databus_mediator, host, port)
        self.resp_app_set = conpot_cmdrsp.c_SetCommandResponder(
            self.snmpEngine, snmpContext, self.databus_mediator, host, port)
        self.resp_app_next = conpot_cmdrsp.c_NextCommandResponder(
            self.snmpEngine, snmpContext, self.databus_mediator, host, port)
        self.resp_app_bulk = conpot_cmdrsp.c_BulkCommandResponder(
            self.snmpEngine, snmpContext, self.databus_mediator, host, port)