コード例 #1
0
ファイル: snmp-receiver.py プロジェクト: sanuma02/Automation
def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
    try:
        #Enables pysmi debugging
        #debug.setLogger(debug.Debug('reader'))

        # Assemble MIB viewer
        mibBuilder = builder.MibBuilder()
        mibViewController = view.MibViewController(mibBuilder)

        # Pre-load MIB modules we expect to work with
        try:
            mibBuilder.loadModules('SNMPv2-MIB')
        except:
            logging.error("Fail loading mibs")

        # vars to store, match here the MIB field you need to save
        # cLApName = '1.3.6.1.4.1.9.9.513.1.1.1.1.5.0'
        # cLApRogueApMacAddress = '1.3.6.1.4.1.9.9.513.3.2.0'
        # cLApDot11IfType = '1.3.6.1.4.1.9.9.513.1.2.1.1.2.0'

        while wholeMsg:
            msgVer = int(api.decodeMessageVersion(wholeMsg))
            if msgVer in api.protoModules:
                pMod = api.protoModules[msgVer]
            else:
                print('Unsupported SNMP version %s' % msgVer)
                logging.error('Unsupported SNMP version %s' % msgVer)
                return
            reqMsg, wholeMsg = decoder.decode(
                wholeMsg,
                asn1Spec=pMod.Message(),
            )
            print('Notification message from %s:%s: ' %
                  (transportDomain, transportAddress))
            logging.info('Notification message from %s:%s: ' %
                         (transportDomain, transportAddress))
            reqPDU = pMod.apiMessage.getPDU(reqMsg)
            if reqPDU.isSameTypeWith(pMod.TrapPDU()):
                if msgVer == api.protoVersion1:
                    varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU)
                else:
                    varBinds = pMod.apiPDU.getVarBinds(reqPDU)

                print('Var-binds:')
                logging.info(
                    '--------------------------------------------------------------------'
                )
                logging.info('Var-binds:')

                trap = TrapEvent()
                for oid, val in varBinds:
                    print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
                trap.sender = str(transportAddress[0])
                # trap.persistToDB()

        return wholeMsg
    except Exception as e:
        trap = TrapEvent()
        logging.error(str(e))
        trap.persistLogToDB(str(e))
コード例 #2
0
ファイル: base.py プロジェクト: nsxsoft/labSNMP
    def __init__(self, ip):
        # FIXME: Use environmental variable to enable PySNMP to load compiled
        # MIBs.
        environ['PYSNMP_MIB_PKGS'] = py_mib_path

        self.ip = ip
        self.mibBuilder = builder.MibBuilder()
コード例 #3
0
def checkSNMP(community, host, port, oid):
    mibBuilder = builder.MibBuilder()
    mibViewController = view.MibViewController(mibBuilder)
    compiler.addMibCompiler(mibBuilder,
                            sources=['http://mibs.snmplabs.com/asn1/@mib@'])
    mibBuilder.loadModules('RFC1213-MIB', 'IF-MIB')
    objectIdentity = rfc1902.ObjectIdentity(oid).resolveWithMib(
        mibViewController)

    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(SnmpEngine(), CommunityData(community),
               UdpTransportTarget((host, port), timeout=1.5, retries=0),
               ContextData(), ObjectType(objectIdentity)))

    if errorIndication:
        print(errorIndication, " : ", host)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for varBind in varBinds:
            varB = (' = '.join([x.prettyPrint() for x in varBind]))
            resultado = " ".join(varB.split()[2:])
            return resultado
    return -1
コード例 #4
0
def translate_mib(custom_mib_paths, load_mib_modules, name, val):
    """
    Translate OID to MIB
    custom_mib_paths: comma separated mib paths as a string
    load_mib_modules: MIB Module to load e.g. "MIB-FILE-1,MIB-FILE-2"
    Return: Translated OID string and value
    """
    if custom_mib_paths and load_mib_modules:
        try:
            mibBuilder = builder.MibBuilder()
            compiler.addMibCompiler(mibBuilder, sources=custom_mib_paths)
            mibViewController = view.MibViewController(mibBuilder)
            temp_load_mib_modules = load_mib_modules.split(',')
            mibBuilder.loadModules(*temp_load_mib_modules)
        except error.MibNotFoundError as excep:
            testcase_Utils.pNote(" {} Mib Not Found!".format(excep), "Error")
    temp_type = val.__class__.__name__
    if custom_mib_paths and load_mib_modules:
        output = rfc1902.ObjectType(rfc1902.ObjectIdentity(name),
                                    val).resolveWithMib(mibViewController).prettyPrint()
        op_list = output.split(" = ")
        name = op_list[0].strip()
        t_val = op_list[1].strip()
        if temp_type == "Integer":
            testcase_Utils.pNote('%s = %s(%s): %s' %
                                 (name, temp_type, val.prettyPrint(), t_val))
        else:
            if t_val == '': #For empty String
                testcase_Utils.pNote('%s = %s: ""' % (name, temp_type))
            else:
                testcase_Utils.pNote('%s = %s: %s' % (name, temp_type, t_val))
        return name, t_val
    else:
        testcase_Utils.pNote('%s = %s: %s' % (name.prettyPrint(), temp_type, val.prettyPrint()))
        return name.prettyPrint(), val.prettyPrint()
コード例 #5
0
def consultaSNMP(comunidad,host,oid):
		mibBuilder = builder.MibBuilder()
		mibViewController = view.MibViewController(mibBuilder)
		compiler.addMibCompiler(mibBuilder, sources=['file:///usr/local/lib/python2.7/dist-packages/pysnmp/smi/mibs',
																						 'http://mibs.snmplabs.com/asn1/@mib@'])
		mibBuilder.loadModules('RFC1213-MIB','IF-MIB')
		objectIdentity = rfc1902.ObjectIdentity(oid).resolveWithMib(mibViewController)

		errorIndication, errorStatus, errorIndex, varBinds = next(
				getCmd(SnmpEngine(),
							 CommunityData(comunidad),
							 UdpTransportTarget((host, 161)),
							 ContextData(),
							 #ObjectType(ObjectIdentity(oid))))
							 ObjectType( objectIdentity )))

		if errorIndication:
				print(errorIndication)
		elif errorStatus:
				print('%s at %s' % (errorStatus.prettyPrint(),errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
		else:

				for varBind in varBinds:
						varB=(' = '.join([x.prettyPrint() for x in varBind]))
						resultado= " ".join(varB.split()[2:])
		return resultado
コード例 #6
0
ファイル: snmp.py プロジェクト: justkrys/snmp_adapter
def listen(
    address=DEFAULT_ADDRESSS,
    port=DEFAULT_PORT,
    community=DEFAULT_COMMUNITY,
    mibs=DEFAULT_MIBS,
):
    """Listen to and SNMP trap and print events."""
    # Based on pySNMP example code.
    mib_builder = builder.MibBuilder()
    compiler.addMibCompiler(mib_builder)
    mib_builder.loadModules(*mibs)
    global _view_controller
    _view_controller = view.MibViewController(mib_builder)
    loop = asyncio.get_event_loop()
    snmp_engine = engine.SnmpEngine()
    print(f"Agent is listening SNMP Trap on {address}, Port: {port}")
    if port < 1024:
        print(
            "WARNING: Port < 1024. Root priviledges or authbind required on *nix systems."
        )
    print("-" * 79)
    config.addTransport(
        snmp_engine,
        udp.domainName + (1, ),
        udp.UdpTransport().openServerMode((address, port)),
    )
    config.addV1System(snmp_engine, community, community)
    ntfrcv.NotificationReceiver(snmp_engine, _listen_callback)
    print("Press CTRL-C to quit.")
    loop.run_forever()
コード例 #7
0
ファイル: oid_db.py プロジェクト: rtbrick/bdsSnmpAdaptor
    def __init__(self, args):
        configDict = loadConfig(args.config)

        self.moduleLogger = set_logging(configDict, __class__.__name__)

        self.moduleLogger.debug('configDict:{}'.format(configDict))

        mibBuilder = builder.MibBuilder()
        self._mibViewController = view.MibViewController(mibBuilder)

        compiler.addMibCompiler(
            mibBuilder, sources=configDict['snmp'].get('mibs', ()))

        # this dict holds all OID items indexed by MIB symbols
        self._mibObjects = collections.defaultdict(dict)

        # this dict holds only recently updated OIDs (indexed by
        # MIB name and object)
        self._candidateMibObjects = collections.defaultdict(dict)

        # this dict holds all OID items populated from `mibObjects`
        self._oids = {}

        self._expireBy = time.time() + self.EXPIRE_PERIOD

        self._dirty = True  # OIDs need sorting
コード例 #8
0
ファイル: snmp.py プロジェクト: xbeaudouin/exaddos
    def _init(self):
        from pysnmp.smi import builder

        mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'IF-MIB')

        self.collection = {
            'ifHCInOctets':
            mibBuilder.importSymbols('IF-MIB', 'ifHCInOctets')[0].getName() +
            (self.interface.snmp_index_vlan, ),
            'ifHCInUcastPkts':
            mibBuilder.importSymbols('IF-MIB', 'ifHCInUcastPkts')[0].getName()
            + (self.interface.snmp_index_vlan, ),
            'ifInNUcastPkts':
            mibBuilder.importSymbols('IF-MIB', 'ifInNUcastPkts')[0].getName() +
            (self.interface.snmp_index_port, ),
            'ifInErrors':
            mibBuilder.importSymbols('IF-MIB', 'ifInErrors')[0].getName() +
            (self.interface.snmp_index_port, ),
            'ifInDiscards':
            mibBuilder.importSymbols('IF-MIB', 'ifInDiscards')[0].getName() +
            (self.interface.snmp_index_port, ),
            'sysDescr':
            mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr')[0].getName() +
            (0, ),
        }

        try:
            self.description = str(self._get('sysDescr') or '-')
            self.running = True
        except KeyboardInterrupt:
            self.running = False
コード例 #9
0
    def __init__(self, host, public, private, port=161, timeout=1, retries=2):
        """Create the snmpy object.

        :param host: hostname or IP address of the device to communicate with
        :type host: str
        :param public: public community string
        :type public: str
        :param private: private community string
        :type private: str
        :param port: port number to connect on (default 161)
        :type port: int
        :param timeout: timeout, in seconds (default 1s)
        :type timeout: int
        :param retries: number of retries (default 2)
        :type retries: int
        :returns: new Snmpy object
        :rtype: Snmpy
        """
        self._host = host
        self._port = port
        self._timeout = timeout
        self._retries = retries
        self._transport = cmdgen.UdpTransportTarget((self._host, self._port),
                                                    timeout=self._timeout,
                                                    retries=self._retries)
        self._public = cmdgen.CommunityData(public, mpModel=self.VERSION_2_2C)
        self._private = cmdgen.CommunityData(private,
                                             mpModel=self.VERSION_2_2C)

        self._mib_builder = builder.MibBuilder()
        self._mib_view_controller = view.MibViewController(self._mib_builder)

        # Pre-load some commonly used modules.
        self.load_mibs('SNMPv2-MIB', 'IF-MIB', 'IP-MIB', 'HOST-RESOURCES-MIB',
                       'FIBRE-CHANNEL-FE-MIB')
コード例 #10
0
 def test_all_mibs(self):
     mibs = filter(is_mib,
                   map(abspath, os.listdir(os.path.dirname(__file__))))
     self.failUnless(mibs, "No mibs found.")
     mibs.sort()
     for mib_name in map(lambda x: x[:-3], mibs):
         mib_builder = builder.MibBuilder()
         mib_builder.loadModules(mib_name)
コード例 #11
0
    def getMibViewController(userCache):
        try:
            mibViewController = userCache['mibViewController']

        except KeyError:
            mibViewController = view.MibViewController(builder.MibBuilder())
            userCache['mibViewController'] = mibViewController

        return mibViewController
コード例 #12
0
ファイル: databus_mediator.py プロジェクト: xushuo1/conpot
    def get_response(self, reference_class, OID):
        if OID in self.oid_map:
            if reference_class == "DisplayString":
                (response_class, ) = builder.MibBuilder().importSymbols(
                    "SNMPv2-TC", "DisplayString")

            elif reference_class == "OctetString":
                (response_class, ) = builder.MibBuilder().importSymbols(
                    "ASN1", "OctetString")

            elif reference_class == "Integer32":
                (response_class, ) = builder.MibBuilder().importSymbols(
                    "SNMPv2-SMI", "Integer32")

            elif reference_class == "Counter32":
                (response_class, ) = builder.MibBuilder().importSymbols(
                    "SNMPv2-SMI", "Counter32")

            elif reference_class == "Gauge32":
                (response_class, ) = builder.MibBuilder().importSymbols(
                    "SNMPv2-SMI", "Gauge32")

            elif reference_class == "TimeTicks":
                (response_class, ) = builder.MibBuilder().importSymbols(
                    "SNMPv2-SMI", "TimeTicks")
            # TODO: All mode classes - or autodetect'ish?
            else:
                # dynamic responses are not supported for this class (yet)
                return False
            response_value = self.databus.get_value(self.oid_map[OID])
            return response_class(response_value)
        else:
            return None
コード例 #13
0
 def start(self):
     self.__lock.acquire()
     try:
         self.__mib_builder = builder.MibBuilder()
         self.__mib_view = view.MibViewController(self.__mib_builder)
     finally:
         self.__lock.release()
     # Load some common MIBs:
     self.load_mib('SNMP-COMMUNITY-MIB')
     self.load_mib('SNMP-VIEW-BASED-ACM-MIB')
     self.load_mib('IF-MIB')
     super(SNMP, self).start()
     return
コード例 #14
0
    def _mib_builder(self):
        """Loads given set of mib files from given path."""
        mib_builder = builder.MibBuilder()
        try:
            self.mib_view_controller = view.MibViewController(mib_builder)

            # set mib path to mib_builder object and load mibs
            mib_path = builder.DirMibSource(self.snmp_mib_path),
            mib_builder.setMibSources(*mib_path)
            if len(MIB_LOAD_LIST) > 0:
                mib_builder.loadModules(*MIB_LOAD_LIST)
        except Exception:
            raise ValueError("Mib load failed.")
コード例 #15
0
ファイル: poller.py プロジェクト: johnnyfontana/shinken
    def set_mib_mibsources(self, mibs, mibSources):
        # logger.warning("[SnmpPoller] set_mib_mibsources %s %s", mibs, mibSources)
        self.mibs = mibs
        self.mibSources = mibSources

        self.mibBuilder = builder.MibBuilder()
        extraMibSources = tuple(
            [builder.DirMibSource(d) for d in self.mibSources])
        totalMibSources = extraMibSources + self.mibBuilder.getMibSources()
        self.mibBuilder.setMibSources(*totalMibSources)
        if self.mibs:
            self.mibBuilder.loadModules(*self.mibs)
        self.mibViewController = view.MibViewController(self.mibBuilder)
コード例 #16
0
ファイル: snmptraprcv.py プロジェクト: Nucleoos/quinn
    def recvcallback(self, snmpEngine, contextEngineId, contextName, varBinds,
                     cbCtx):

        mibBuilder = builder.MibBuilder()
        mibBuilder.setMibPath(
            'MIB', '/usr/lib/pymodules/python2.5/pysnmp/v4/smi/mibs/',
            '/usr/share/python-support/python-pysnmp4/pysnmp/v4/smi/mibs/')
        #mibBuilder.loadModules('CPQPOWER')

        print 'Notification from SNMP Engine \"%s\", Context \"%s\"' % (
            contextEngineId, contextName)
        for name, val in varBinds:
            print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
コード例 #17
0
def mib_builder(custom_mib_path, LOAD_MIB_MODULE):
    mibBuilder = builder.MibBuilder()
    try:
        if custom_mib_path:
            compiler.addMibCompiler(mibBuilder, sources=custom_mib_path.split(
              ","))
        global mibViewController
        mibViewController = view.MibViewController(mibBuilder)
        if LOAD_MIB_MODULE:
            _mibs=LOAD_MIB_MODULE.split(",")
            mibBuilder.loadModules(*_mibs)
    except error.MibNotFoundError as excep:
        print(" {} Mib Not Found!".format(excep))
コード例 #18
0
ファイル: traplistener.py プロジェクト: FlyearthR/lingi2142-1
def main():
    # Instantiate snmp engine
    snmpEngine = engine.SnmpEngine()

    # Load MIBs (for translation of the numeric OIDs)
    mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB')
    mibViewController = view.MibViewController(mibBuilder)

    # Transport setup
    # UDP over IPv6, listening interface/port
    config.addTransport(
        snmpEngine,
        udp6.domainName + (1,),
        udp6.Udp6Transport().openServerMode(('::', TRAP_PORT))
    )

    # SNMPv2c setup
    # SecurityName <-> CommunityName mapping
    config.addV1System(snmpEngine, 'my-area', 'public')


    # Callback function for receiving notifications
    # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
    def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
            varBinds, cbCtx):
        # Translate numerical OIDs into human readable form
        varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]

        # Turn on write permission for everyone
        os.umask(0)
        # Open file, append new data at the end
        with open(os.open(TRAP_LOG_PATH, os.O_CREAT | os.O_WRONLY, 0o777), 'a+') as f:
            t = time.gmtime()
            f.write('TRAP received on %s from ContextEngineId "%s", ContextName "%s" \n' % (time.strftime('%c', t), contextEngineId.prettyPrint(),
                                                                            contextName.prettyPrint()))
            # Write data in file
            for varbind in varBinds:
                f.write(varbind.prettyPrint()+'\n')
            f.write('\n')
            
    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmpEngine, cbFun)

    snmpEngine.transportDispatcher.jobStarted(1)  # Start a job that will never finish

    # Run I/O dispatcher which would receive queries and send confirmations
    try:
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
コード例 #19
0
 def get_first_node_name(mib_filepath, mib_filename):
     """
     Get the node name from the given mib file path and file name
     :param mib_filepath: Mib file path of the git url or abs file path
     :param mib_filename: MIB file name
     :return: oid, lable, suffix, mibView, mibBuilder
     """
     mibBuilder = builder.MibBuilder()
     compiler.addMibCompiler(mibBuilder, sources=mib_filepath.split(","))
     for mib in mib_filename.split(","):
         mibBuilder.loadModules(mib)
     mibView = view.MibViewController(mibBuilder)
     oid, label, suffix = mibView.getFirstNodeName()
     return oid, label, suffix, mibView, mibBuilder
コード例 #20
0
    def __init__(self):
        # Check for already existing file
        # target_file_name = str(random.random()) + '.txt'
        self.target_file_name = '1.txt'
        self.community_name = 'public'

        # Initialize counter to zero
        self.counter = 0

        # Create command generator
        self.engine = engine.SnmpEngine()
        self.gen = cmdgen
        self.cmdgen = self.gen.CommandGenerator(self.engine)
        self.build = builder.MibBuilder()
コード例 #21
0
ファイル: switch.py プロジェクト: thechristschn/hpswitch
    def __init__(self, hostname, community="public"):
        self.hostname = hostname
        self.community = community

        mib_builder = builder.MibBuilder()
        mib_builder.setMibPath(*(mib_builder.getMibPath() + (sys.path[0], )))
        mib_builder.loadModules('RFC1213-MIB', 'BRIDGE-MIB', 'IF-MIB',
                                'Q-BRIDGE-MIB', 'IP-MIB', 'HP-ICF-IPCONFIG')

        self.mib_view_controller = view.MibViewController(mib_builder)

        self.command_generator = cmdgen.CommandGenerator()
        self.command_generator.mibViewController = view.MibViewController(
            mib_builder)
コード例 #22
0
def getMIBViewer():
    # Create MIB loader/builder
    mibBuilder = builder.MibBuilder()

    #    log.info('Loading MIB modules...')
    #    mibBuilder.loadModules(
    #        'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB', "IF-MIB"
    #        )
    #    log.info('done')

    log.info('Indexing MIB objects...')
    mibView = view.MibViewController(mibBuilder)
    log.info('done')

    return mibView
コード例 #23
0
    def _mib_builder(self):
        """Loads the MIB files and creates dicts with hierarchical structure"""

        # Create MIB loader/builder
        mibBuilder = builder.MibBuilder()

        self._log_debug('Reading MIB sources...')
        mibSources = mibBuilder.getMibSources() + (
            builder.DirMibSource('/etc/sspl-ll/templates/snmp'), )
        mibBuilder.setMibSources(*mibSources)

        self._log_debug("MIB sources: %s" % str(mibBuilder.getMibSources()))
        for module in self._enabled_MIBS:
            mibBuilder.loadModules(module)
        self._mibView = view.MibViewController(mibBuilder)
コード例 #24
0
ファイル: TrippLite.py プロジェクト: cdfredrick/AstroComb_HPF
 def __init__(self, ip_address, outlet_id, timeout=1, retries=5):
     self.mib = 'TRIPPLITE-PRODUCTS'
     self.transport_addr = (str(ip_address), 161)
     self.transport_target = UdpTransportTarget(self.transport_addr,
                                                timeout=timeout,
                                                retries=retries)
     self.outlet_id = int(outlet_id)
     self.device_id = 1
     self.community = CommunityData('tripplite')
     # Initialize the MIB
     mibBuilder = builder.MibBuilder()
     mibView = view.MibViewController(mibBuilder)
     obj_id = rfc1902.ObjectIdentity(self.mib)
     obj_id.addAsn1MibSource('file://@mib@')
     obj_id.addAsn1MibSource('http://mibs.snmplabs.com/asn1/@mib@')
     obj_id.resolveWithMib(mibView)
コード例 #25
0
ファイル: snmp.py プロジェクト: SrijaGupta/file
    def create_object_identity(self, **kwargs):
        """
        :param
            oid: **REQUIRED** OID or MibSymbol
            value: **OPTION** value for snmp set
        :return: ObjectIdentity
        """
        t.log("DEBUG", "Entering 'create_object_identity'\n"+__file__)
        oid = kwargs.get('oid')
        value = kwargs.get('value')
        oidre = re.match(r'(.*)::(.*)\.(.*)', oid)
        mib_name = ''
        oid_name = ''
        if oidre:
            mib_name = oidre.group(1)
            oid_name = oidre.group(2)
            oid_index = oidre.group(3)
            object_identity = ObjectIdentity(
                mib_name, oid_name, oid_index).addAsn1MibSource(self.mibs_dir)
        else:
            oidre = re.match('(.*)::(.*)', oid)
            if oidre:
                mib_name = oidre.group(1)
                oid_name = oidre.group(2)
                object_identity = ObjectIdentity(mib_name, oid_name).addAsn1MibSource(self.mibs_dir)

        if re.match(r'^([0-9]*\.)*[0-9]*$', oid):
            object_identity = ObjectIdentity(oid).addAsn1MibSource(
                self.mibs_dir)
        elif re.match(r'^([a-z A-Z 0-9 \-]*\.)*[a-z A-Z 0-9 \-]*$', oid):
            from pysnmp.smi import builder, view
            mibbuilder = builder.MibBuilder()
            mibviewcontroller = view.MibViewController(mibbuilder)
            objectidentity1 = ObjectIdentity(oid)
            objectidentity1.resolveWithMib(mibviewcontroller)
            oid = '.'.join(map(str, objectidentity1.getOid().asTuple()))
            object_identity = ObjectIdentity(oid).addAsn1MibSource(
                self.mibs_dir)

        if self.mibs_custom_dir:
            t.log('DEBUG', "Created Object Identity with custom mib directory: "+self.mibs_custom_dir)
            object_identity = object_identity.addMibSource(self.mibs_custom_dir)
        if value:
            object_type = ObjectType(object_identity, value)
        else:
            object_type = ObjectType(object_identity)
        return object_type
コード例 #26
0
 def snmpGETNEXT(self, input_var):
     splited = input_var.split(" =")
     mib_symbol = splited[0]
     mib_identifier = [mib_symbol.split("::")[0]]
     object_symbol = mib_symbol.split("::")[1]
     object_path = object_symbol.split(".")
     complete_path = tuple(mib_identifier + object_path)
     mibBuilder = builder.MibBuilder()
     mibViewController = view.MibViewController(mibBuilder)
     objectIdentity = ObjectIdentity(*complete_path)
     objectIdentity.resolveWithMib(mibViewController)
     if self.snmpVer == "version3":
         errorIndication, errorStatus, errorIndex, varBinds = next(
             nextCmd(
                 SnmpEngine(),
                 UsmUserData(userName=self.userName,
                             authKey=self.authPass,
                             privKey=self.privPass,
                             authProtocol=self.authProtocol,
                             privProtocol=self.privProtocol,
                             securityEngineId=None,
                             securityName=None),
                 UdpTransportTarget((self.ip, 161)), ContextData(),
                 ObjectType(ObjectIdentity(objectIdentity.getOid()))))
         if errorIndication:
             return errorIndication
         elif errorStatus:
             return '%s at %s' % (errorStatus.prettyPrint(), errorIndex and
                                  varBinds[int(errorIndex) - 1][0] or '?')
         else:
             for varBind in varBinds:
                 return ' = '.join([x.prettyPrint() for x in varBind])
     else:
         errorIndication, errorStatus, errorIndex, varBinds = next(
             nextCmd(SnmpEngine(), CommunityData(self.comminutyString),
                     UdpTransportTarget((self.ip, 161)), ContextData(),
                     ObjectType(ObjectIdentity(self.mibOid))))
         if errorIndication:
             return errorIndication
         elif errorStatus:
             return '%s at %s' % (errorStatus.prettyPrint(), errorIndex and
                                  varBinds[int(errorIndex) - 1][0] or '?')
         else:
             for varBind in varBinds:
                 return ' = '.join([x.prettyPrint() for x in varBind])
コード例 #27
0
ファイル: trap_receiver.py プロジェクト: merliyatf/delfin
    def _mib_builder(self):
        """Loads given set of mib files from given path."""
        mib_builder = builder.MibBuilder()
        try:
            self.mib_view_controller = view.MibViewController(mib_builder)

            # Append custom mib path to default path for loading mibs
            mib_sources = mib_builder.getMibSources() + (builder.DirMibSource(
                self.snmp_mib_path),)
            mib_builder.setMibSources(*mib_sources)
            files = []
            for file in os.listdir(self.snmp_mib_path):
                # Pick up all .py files, remove extenstion and load them
                if file.endswith(MIB_LOAD_FILE_FORMAT):
                    files.append(os.path.splitext(file)[0])
            if len(files) > 0:
                mib_builder.loadModules(*files)
        except Exception:
            raise ValueError("Mib load failed.")
コード例 #28
0
    def __init__(self,
                 additional_mib_search_paths=[],
                 additional_mib_load_modules=[],
                 debug=False,
                 load_texts=True):
        if debug:  # Enable Debugging
            pysnmp_debug.setLogger(pysnmp_debug.Debug('all'))

        # The pysnmp libraries will compile MIB files into python files, and
        #   store them on the system in a cache directory under ~/.pysnmp/mibs
        #   It only needs to do this once as it encounters new MIBs, and not
        #   every time you run this program.  Order of the loading matters.
        mib_modules = additional_mib_load_modules + DEFAULT_MIB_LOAD_MODULES
        mib_sources = additional_mib_search_paths + DEFAULT_MIB_SEARCH_PATHS
        self.mibBuilder = builder.MibBuilder()
        self.mibBuilder.loadTexts = load_texts  # Loads mib text descriptions
        compiler.addMibCompiler(self.mibBuilder, sources=mib_sources)
        self.mibBuilder.loadModules(*mib_modules)
        self.mibView = view.MibViewController(self.mibBuilder)
コード例 #29
0
 def create_trap_listner_job(cls, port="162"):
     """
     Create Trap listner job
     :param port:
     :return:None
     """
     mibBuilder = builder.MibBuilder()
     custom_mib_path = cls.data_repo.get("custom_mib_path")
     load_mib_module = cls.data_repo.get("load_mib_module")
     temp_custom_mib_paths = []
     if custom_mib_path and load_mib_module:
         custom_mib_paths = custom_mib_path.split(',')
         for paths in custom_mib_paths:
             paths = paths.strip()
             if 'http' in paths and '@mib@' not in paths:
                 if paths[-1] == '/':
                     paths = paths + '/@mib@'
                 else:
                     paths = paths + '@mib@'
             if 'http' in paths and 'browse' in paths:
                 paths = paths.replace('browse', 'raw')
             if 'http' in paths and 'browse' in paths:
                 paths = paths.replace('browse', 'raw')
             temp_custom_mib_paths.append(paths)
         if os.name == 'posix' and '/usr/share/snmp/' not in custom_mib_path:
             temp_custom_mib_paths.append('/usr/share/snmp/')
         try:
             compiler.addMibCompiler(mibBuilder,
                                     sources=temp_custom_mib_paths)
             cls.mibViewController = view.MibViewController(mibBuilder)
             mibs = load_mib_module.split(",")
             mibBuilder.loadModules(*mibs)
         except error.MibNotFoundError as excep:
             testcase_Utils.pNote("{} Mib Not Found!".format(excep),
                                  "Error")
     snmpEngine = cls.get_asyncoredispatcher(port)
     udptransport = udp.UdpTransport()
     cls.udptransport.update({"udptransport{}".format(port): udptransport})
     config.addTransport(
         snmpEngine, udp.domainName,
         udptransport.openServerMode(('0.0.0.0', int(port))))
     snmpEngine.transportDispatcher.jobStarted(1)
コード例 #30
0
def mibTextToPy(mib_path):
    """ Convert mibs to a format that pysnmp can actually use. 
    """

    logging.info("Setting MIB Path")
    cmdGen = cmdgen.CommandGenerator() 

    mibBuilder = builder.MibBuilder()
    mibBuilder = cmdGen.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder 
    mibSources = mibBuilder.getMibSources() + (builder.DirMibSource(mib_path), )
    mibBuilder.setMibSources(*mibSources)
    logging.info(mibBuilder.getMibSources())

    if os.path.isdir(mib_path):
        for mib in MIB_SRCLIST:
            mib_preload = mib[0]
            mib_srcname = mib[1]
            mib_destname = mib[2]
            if not os.path.isfile(os.path.join(mib_path, mib_srcname)):
                logging.critical("FAILED: Required MIB %s is missing from \
                                  path %s") % (mib_srcname, mib_path)
                return 1
            logging.info("Converting MIB to py")
            if mib_preload: 
                cmd = "smidump -k -p %s -f python %s | libsmi2pysnmp > %s" % \
                      (os.path.join(mib_path, mib_preload),
                       os.path.join(mib_path, mib_srcname),
                       os.path.join(mib_path, mib_destname) + ".py")
            else:
                cmd = "smidump -k -f python %s | libsmi2pysnmp > %s" % \
                      (os.path.join(mib_path, mib_srcname),
                       os.path.join(mib_path, mib_destname) + ".py")
            logging.info(cmd)
            os.system(cmd)
            logging.info("Loading MIB")
            mibBuilder.loadModules(mib_destname)
            logging.info(mib_destname)
    else:
        logging.critical("FAILED: MIB directory %s is not present") % mib_path
        return 1

    return cmdGen