def outlet_state(self, set_state=None): '''The current state of the outlet. Setting this value to turnOff(1) will turn off the outlet. Setting this value to turnOn(2) will turn on the outlet. Setting this value to cycle(3) will turn the outlet off, then turn it back on: 0 = idle or unknown 1 = off 2 = on 3 = cycle (turn off, then turn on ''' if set_state is None: # Get current outlet state obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletState', self.device_id, self.outlet_id) g = getCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id)) errorIndication, errorStatus, errorIndex, varBinds = next(g) oid, value = varBinds[0] return int(value) else: # Send outlet state obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletCommand', self.device_id, self.outlet_id) g = setCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id, int(set_state))) errorIndication, errorStatus, errorIndex, varBinds = next(g)
def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): global pdu_count global mibViewController print "####################### NEW Notification(PDU_COUNT: {}) #######################".format( pdu_count) execContext = snmpEngine.observer.getExecutionContext( 'rfc3412.receiveMessage:request') print( '#Notification from %s \n#ContextEngineId: "%s" \n#ContextName: "%s" \n#SNMPVER "%s" \n#SecurityName "%s"' % ('@'.join([str(x) for x in execContext['transportAddress']]), contextEngineId.prettyPrint(), contextName.prettyPrint(), execContext['securityModel'], execContext['securityName'])) for oid, val in varBinds: output = rfc1902.ObjectType( rfc1902.ObjectIdentity(oid), val).resolveWithMib(mibViewController).prettyPrint() print output pdu_count += 1
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()
def _parse(self): """ translate the trap msg with the mib viewer """ for name, val in self._var_binds: var_bind = rfc1902.ObjectType(rfc1902.ObjectIdentity(name), val) var_bind.resolveWithMib(self._viewer) obj_name = var_bind[0].getMibSymbol()[1] value = var_bind[1].prettyPrint() self._parsed_data[obj_name] = value
def _cb_fun(self, state_reference, context_engine_id, context_name, var_binds, cb_ctx): """Callback function to process the incoming trap.""" exec_context = self.snmp_engine.observer.getExecutionContext( 'rfc3412.receiveMessage:request') LOG.info('#Notification from %s \n#ContextEngineId: "%s" ' '\n#ContextName: ''"%s" \n#SNMPVER "%s" \n#SecurityName "%s" ' % ( '@'.join( [str(x) for x in exec_context['transportAddress']]), context_engine_id.prettyPrint(), context_name.prettyPrint(), exec_context['securityModel'], exec_context['securityName'])) try: # transportAddress contains both ip and port, extract ip address source_ip = exec_context['transportAddress'][0] alert_source = self._get_alert_source_by_host(source_ip) # In case of non v3 version, community string is used to map the # trap. Pysnmp library helps to filter traps whose community string # are not configured. But if a given community name x is configured # for storage1, if the trap is received with x from storage 2, # library will allow the trap. So for non v3 version, we need to # verify that community name is configured at alert source db for # the storage which is sending traps. # context_name contains the incoming community string value if exec_context['securityModel'] != constants.SNMP_V3_INT \ and alert_source['community_string'] != str(context_name): msg = (_("Community string not matching with alert source %s, " "dropping it.") % source_ip) raise exception.InvalidResults(msg) var_binds = [rfc1902.ObjectType( rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib( self.mib_view_controller) for x in var_binds] alert = {} for var_bind in var_binds: oid, value = self._extract_oid_value(var_bind) alert[oid] = value # Fill additional info to alert info alert['transport_address'] = source_ip alert['storage_id'] = alert_source['storage_id'] # Handover to alert processor for model translation and export alert_processor.AlertProcessor().process_alert_info(alert) except (exception.AlertSourceNotFound, exception.StorageNotFound, exception.InvalidResults) as e: # Log and end the trap processing error flow LOG.error(e) except Exception as e: # Unexpected exception occurred LOG.error(e)
def outlet_ramp_delay(self, set_delay=None): '''The number of seconds to delay before powering on the given outlet: integer values only ''' if set_delay is None: # Get current outlet state obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampDelay', self.device_id, self.outlet_id) g = getCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id)) errorIndication, errorStatus, errorIndex, varBinds = next(g) oid, value = varBinds[0] return int(value) else: # Send outlet state obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampDelay', self.device_id, self.outlet_id) g = setCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id), int(set_delay)) errorIndication, errorStatus, errorIndex, varBinds = next(g)
def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): logTime=datetime.now().strftime("%m/%d/%Y-%H:%M:%S.%f")[:-3] writeLogs('\n\n{}\nNotification from ContextEngineId "{}", ContextName "{}"'.format(logTime,contextEngineId.prettyPrint(), contextName.prettyPrint())) print('\nNotification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds] for varBind in varBinds: writeLogs('\n' + varBind.prettyPrint()) print(varBind.prettyPrint()) writeLogs('\n')
def outlet_ramp_action(self, set_action=None): '''The ramp action to take on a given outlet when powering on the device: 0 = remain off 1 = turn on after delay ''' if set_action is None: # Get current outlet state obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampAction', self.device_id, self.outlet_id) g = getCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id)) errorIndication, errorStatus, errorIndex, varBinds = next(g) oid, value = varBinds[0] return int(value) else: # Send outlet state obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampAction', self.device_id, self.outlet_id) g = setCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id, int(set_action))) errorIndication, errorStatus, errorIndex, varBinds = next(g)
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')
def query(self, oid, base=False): # Get current outlet state if base: obj_id = rfc1902.ObjectIdentity(self.mib, oid) else: obj_id = rfc1902.ObjectIdentity(oid) g = getCmd(SnmpEngine(), self.community, self.transport_target, ContextData(), rfc1902.ObjectType(obj_id)) errorIndication, errorStatus, errorIndex, varBinds = next(g) print(errorIndication, '\n') print(errorStatus, '\n') print(errorIndex, '\n') print(varBinds, '\n') oid, value = varBinds[0] print(varBinds[0].prettyPrint(), '\n') print(oid, '\n') print(value, '\n')
def trap_decoder(cls, snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): """ Decode the trap messages and saves it in to data repository This is call back method which will be coalled internaly for each trap message :param transportDispatcher: :param transportDomain: :param transportAddress: :param wholeMsg: :return: the actual ASN1 data dumps """ ticks = time.ctime() transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo( stateReference)[-1][0] if not cls.data_repo.get( "snmp_trap_messages_{}".format(transportAddress)): cls.data_repo.update( {"snmp_trap_messages_{}".format(transportAddress): []}) execContext = snmpEngine.observer.getExecutionContext( 'rfc3412.receiveMessage:request') decoded_msg = [] decoded_msg.append({"time_stamp": ticks}) decoded_msg.append({"contextEngineId": contextEngineId.prettyPrint()}) decoded_msg.append({"SNMPVER": execContext["securityModel"]}) decoded_msg.append({"securityName": execContext['securityName']}) for oid, val in varBinds: try: output = rfc1902.ObjectType( rfc1902.ObjectIdentity(oid), val).resolveWithMib(cls.mibViewController).prettyPrint() except error.SmiError as excep: testcase_Utils.pNote("{} Decode Error!".format(excep), "Error") op_list = output.split(" = ") oid = op_list[0].strip() value = op_list[1].strip() decoded_msg.append((oid, value)) temp_decoded_msg = cls.data_repo.get( "snmp_trap_messages_{}".format(transportAddress)) temp_decoded_msg.append(decoded_msg) cls.data_repo.update({ "snmp_trap_messages_{}".format(transportAddress): temp_decoded_msg })
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here if errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for varBind in varBindRow: print( rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]), varBind[1]).resolveWithMib( mibViewController).prettyPrint()) return 1 # signal dispatcher to continue
def cbReceiverSnmp(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo( stateReference) if (bDebug): szDebug = str( "Notification From: %s, Domain: %s, SNMP Engine: %s, Context: %s" % (transportAddress, transportDomain, contextEngineId.prettyPrint(), contextName.prettyPrint())) print(szDebug) logFile.write(szDebug) logFile.flush() # Create output String szOut = "Trap Source{}, Trap OID {}".format(transportAddress, transportDomain) varBinds = [ rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds ] for name, val in varBinds: # Append to output String szOut = szOut + ", Oid: {}, Value: {}".format(name.prettyPrint(), val.prettyPrint()) if isinstance(val, OctetString): if (name.prettyPrint() != "SNMP-COMMUNITY-MIB::snmpTrapAddress.0"): szOctets = val.asOctets() #.rstrip('\r').rstrip('\n') szOut = szOut + ", Octets: {}".format(szOctets) if (bDebug): print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) outputFile.write(szOut) if "\n" not in szOut: outputFile.write("\n") outputFile.flush()
def _cb_fun(self, state_reference, context_engine_id, context_name, var_binds, cb_ctx): """Callback function to process the incoming trap.""" exec_context = self.snmp_engine.observer.getExecutionContext( 'rfc3412.receiveMessage:request') LOG.info('#Notification from %s \n#ContextEngineId: "%s" ' '\n#ContextName: ' '"%s" \n#SNMPVER "%s" \n#SecurityName "%s" ' % ('@'.join([str(x) for x in exec_context['transportAddress']]), context_engine_id.prettyPrint(), context_name.prettyPrint(), exec_context['securityModel'], exec_context['securityName'])) var_binds = [ rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(self.mib_view_controller) for x in var_binds ] alert = {} for var_bind in var_binds: oid, value = self._extract_oid_value(var_bind) alert[oid] = value # Fill additional info to alert_info # transportAddress contains both ip and port, extract ip address alert['transport_address'] = exec_context['transportAddress'][0] # Handover trap info to alert processor for model translation and export try: alert_processor.AlertProcessor().process_alert_info(alert) except (exception.AccessInfoNotFound, exception.StorageNotFound, exception.InvalidResults) as e: # Log and end the trap processing error flow LOG.error(e) except Exception as e: # Unexpected exception occurred LOG.error(e)
mibSrcs = mb.getMibSources() + (builder.DirMibSource( os.path.join(os.getcwd(), "CompiledMIBs")), ) mb.setMibSources(*mibSrcs) print(mibSrcs) mb.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB', 'PowerNet-MIB', 'UPS-MIB') vc = view.MibViewController(mb) varBinds = [ ('1.3.6.1.2.1.1.3.0', 9041620), ('1.3.6.1.6.3.1.1.4.1.0', '1.3.6.1.4.1.318.0.636'), ('1.3.6.1.4.1.318.2.3.3.0', b'UPS: On battery power in response to distorted input.'), ('1.3.6.1.2.1.33.1.2.3.0', 20), ('1.3.6.1.2.1.33.1.2.2.0', 0), ('1.3.6.1.2.1.33.1.9.7.0', 2), ] for k, v in varBinds: q = tuple(int(kk) for kk in k.split('.')) print(k, q) try: print(vc.getNodeName(q)) except: print("Fail 1!") try: vb = rfc1902.ObjectType(rfc1902.ObjectIdentity(k), v).resolveWithMib(vc) print(vb.prettyPrint()) except: print("Fail 2!")
def add(self, mibName, mibSymbol, *indices, value=None, valueFormat=None, code=None): """Add SNMP MIB managed object instance to the OID DB Args: mibName (str): MIB name e.g. SNMPv2-MIB. This MIB must be in MIB search path. mibSymbol (str): MIB symbol name indices (vararg): one or more objects representing indices. Should be `0` for scalars. value: put this value into MIB managed object. This is what SNMP manager will get in response. The `None` sentinel refreshes existing object. valueFormat (string): 'hexValue' to indicate hex `value` initializer. Optional. code (string): compile and use this Python code snippet for getting a value at run time. Optional. Examples: add('SNMPv2-MIB', 'sysDescr', 0, value='hello world') add('SNMPv2-MIB', 'sysDescr', 0, value='10101010', valueFormat='binValue') add('SNMPv2-MIB', 'sysDescr', 0, code='print("hello world")') """ if value is None: objectIdentity = rfc1902.ObjectIdentity( mibName, mibSymbol, *indices).resolveWithMib(self._mibViewController) try: oidDbItem = self._oids[objectIdentity.getOid()] except KeyError: raise error.BdsError( 'Initial value for managed %s::%s object must be ' 'provided' % (mibName, mibSymbol)) else: obj = rfc1902.ObjectType( rfc1902.ObjectIdentity(mibName, mibSymbol, *indices), value) objectIdentity, objectSyntax = obj.resolveWithMib(self._mibViewController) try: representation = {valueFormat if valueFormat else 'value': value} objectSyntax = objectSyntax.clone(**representation) if code: code = compile(code, '<%s::%s>' % (mibName, mibSymbol), 'exec') oidDbItem = OidDbItem( oid=objectIdentity.getOid(), name=objectIdentity.getMibSymbol()[1], value=objectSyntax, code=code ) except Exception as exc: raise error.BdsError( 'Error setting managed object %s (%s) of type %s to value ' '"%s"' % ('::'.join(objectIdentity.getMibSymbol()), objectIdentity.getOid(), objectSyntax, value)) self.moduleLogger.debug( f'{"updating" if oidDbItem.oid in self._oids else "adding"} ' f'{oidDbItem.oid} {"<code>" if code else oidDbItem.value.prettyPrint()}') # put new OID online immediately self._oids[oidDbItem.oid] = oidDbItem self._dirty = True now = time.time() mibObject = mibName, mibSymbol # We update two DBs for some time while use only one, eventually # we drop the older DB and use the newer one. This effectively # expires DB entries that do not get updated for some time. self._mibObjects[mibObject][oidDbItem.oid] = oidDbItem self._candidateMibObjects[mibObject][oidDbItem.oid] = oidDbItem if self._expireBy < now: # put candidate objects online (self._mibObjects[mibObject], self._candidateMibObjects[mibObject]) = ( self._candidateMibObjects[mibObject], self._mibObjects[mibObject]) # prepare new candidate objects dict - drop everything it has, # most importantly, entries that have not been updated # N.B. this only works for tablular SNMP objects self._candidateMibObjects[mibObject].clear() # stale entries expire in two runs of `.add` self._expireBy = now + self.EXPIRE_PERIOD / 2 # drop all online OIDs self._oids.clear() # put recently updated OIDs online for oidItems in self._mibObjects.values(): self._oids.update(oidItems)
if errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for varBind in varBindRow: print( rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]), varBind[1]).resolveWithMib( mibViewController).prettyPrint()) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [ rfc1902.ObjectType(rfc1902.ObjectIdentity( 'iso.org.dod')).resolveWithMib(mibViewController), rfc1902.ObjectType(rfc1902.ObjectIdentity( 'IF-MIB', 'ifMIB')).resolveWithMib(mibViewController) ], cbFun) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher()
# Assemble MIB browser mibBuilder = builder.MibBuilder() mibViewController = view.MibViewController(mibBuilder) compiler.addMibCompiler(mibBuilder, sources=[ 'file:///usr/share/snmp/mibs', 'http://mibs.snmplabs.com/asn1/@mib@' ]) # Pre-load MIB modules we expect to work with mibBuilder.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB') # This is what we can get in TRAP PDU varBinds = [('1.3.6.1.2.1.1.3.0', 12345), ('1.3.6.1.6.3.1.1.4.1.0', '1.3.6.1.6.3.1.1.5.2'), ('1.3.6.1.6.3.18.1.3.0', '0.0.0.0'), ('1.3.6.1.6.3.18.1.4.0', ''), ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', 'my system')] # Run var-binds through MIB resolver # You may want to catch and ignore resolution errors here varBinds = [ rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds ] for varBind in varBinds: print(varBind.prettyPrint())
print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Another way to obtain the first (or last) symbol in MIB module mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB', '').resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB symbol from whatever MIB it is defined at (MIB should be loaded) mibVar = rfc1902.ObjectIdentity('', 'sysDescr', 0).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Create an OID-value pair (called variable-binding in SNMP) varBind = rfc1902.ObjectType( rfc1902.ObjectIdentity('SNMPv2-MIB', 'sysObjectID', 0), '1.3.6.1').resolveWithMib(mibView) print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint()) # Create just OID varBind = rfc1902.ObjectType( rfc1902.ObjectIdentity('SNMPv2-MIB', 'sysObjectID', 0)).resolveWithMib(mibView) print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint()) # Create var-binds from MIB notification object (without OBJECTS clause) varBinds = rfc1902.NotificationType(