def mib2pysnmp2(mib_file, output_dir):
    """
    The 'build-pysnmp-mib' script we previously used is no longer available
    Latest pysmi has the ability to generate a .py file from .mib automatically

    :param mib_file: path to the .mib file we want to compile
    :param output_dir: path to the output directory
    :return: True if we successfully compile the .mib to a .py
    """

    logger.debug('Compiling mib file: %s', mib_file)

    # create a mib compiler with output dir
    mibCompiler = MibCompiler(SmiV2Parser(), PySnmpCodeGen(),
                              PyFileWriter(output_dir))

    # add sources from where we fetch dependencies
    mibCompiler.addSources(HttpReader('mibs.snmplabs.com', 80, '/asn1/@mib@'))
    mibCompiler.addSources(
        FileReader(os.path.dirname(os.path.abspath(mib_file))))

    # add searchers
    mibCompiler.addSearchers(PyFileSearcher(output_dir))
    mibCompiler.addSearchers(PyPackageSearcher('pysnmp.mibs'))
    mibCompiler.addSearchers(StubSearcher(*baseMibs))

    # compile, there should be a MIBFILE.py generated under output_dir
    mibName = os.path.basename(mib_file).replace('.mib', '')
    results = mibCompiler.compile(mibName)

    if results[mibName] == 'compiled' or results[mibName] == 'untouched':
        return True

    return False
Esempio n. 2
0
def _get_reader_from_url(url):
    from urllib.parse import urlparse

    from pysmi.reader.httpclient import HttpReader

    if not (url.startswith('//') or url.startswith('http://')
            or url.startswith('https://')):
        url = "//" + url
    url_parsed = urlparse(url)
    url_host = url_parsed.hostname
    url_locationTemplate = url_parsed.path
    port = 80
    if url_parsed.port:
        port = url_parsed.port
    return HttpReader(url_host, port, url_locationTemplate)
Esempio n. 3
0
def getReadersFromUrls(*sourceUrls, **options):
    readers = []
    for sourceUrl in sourceUrls:
        mibSource = urlparse.urlparse(sourceUrl)

        if sys.version_info[0:2] < (2, 5):

            class ParseResult(tuple):
                pass

            mibSource = ParseResult(mibSource)

            for k, v in zip(
                ('scheme', 'netloc', 'path', 'params', 'query', 'fragment',
                 'username', 'password', 'hostname', 'port'),
                    mibSource + ('', '', '', None)):
                setattr(mibSource, k, v)

        if not mibSource.scheme or mibSource.scheme == 'file':
            readers.append(FileReader(mibSource.path).setOptions(**options))

        elif mibSource.scheme in ('http', 'https'):
            readers.append(
                HttpReader(
                    mibSource.hostname or mibSource.netloc,
                    mibSource.port or 80,
                    mibSource.path,
                    ssl=mibSource.scheme == 'https').setOptions(**options))

        elif mibSource.scheme in ('ftp', 'sftp'):
            readers.append(
                FtpReader(mibSource.hostname or mibSource.netloc,
                          mibSource.path,
                          ssl=mibSource.scheme == 'sftp',
                          port=mibSource.port or 21,
                          user=mibSource.username or 'anonymous',
                          password=mibSource.password
                          or 'anonymous@').setOptions(**options))

        else:
            raise error.PySmiError('Unsupported URL scheme %s' % sourceUrl)

    return readers
Esempio n. 4
0
#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(
    parserFactory(**smiV1Relaxed)(), 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(*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)
Esempio n. 5
0
from pysmi import debug

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

inputMibs = [ 'IF-MIB', 'IP-MIB' ]
httpSources = [ 
    ('mibs.snmplabs.com', 80, '/asn1/@mib@')
]
ftpSources = [
    ('ftp.cisco.com', '/pub/mibs/v2/@mib@')
]
dstDirectory = '.pysnmp-mibs'

# Initialize compiler infrastructure

mibCompiler = MibCompiler(
    parserFactory(**smiV1Relaxed)(), PySnmpCodeGen(), PyFileWriter(dstDirectory)
)

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

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

# run non-recursive MIB compilation
results = mibCompiler.compile(*inputMibs, **dict(noDeps=True))

print('Results: %s' % ', '.join(['%s:%s' % (x, results[x]) for x in results]))
Esempio n. 6
0
from pysmi.borrower.pyfile import PyFileBorrower
from pysmi.writer.pyfile import PyFileWriter
from pysmi.parser.null import NullParser
from pysmi.codegen.null 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]))