def run_trap_listener(): if not traffy_config.ENABLE_SNMP: print("SNMP not enabled! Exiting...") exit() if not traffy_config.ENABLE_TRAP: print("Trap not enabled! Exiting...") exit() snmp_engine = engine.SnmpEngine() config.addTransport( snmp_engine, udp.domainName, udp.UdpTransport().openServerMode( ("0.0.0.0", traffy_config.TRAP_PORT))) for id in traffy_config.SWITCHES: config.addV3User(snmp_engine, traffy_config.SWITCHES[id]["username"], config.usmHMACSHAAuthProtocol, traffy_config.SWITCHES[id]["password"], config.usmDESPrivProtocol, traffy_config.SWITCHES[id]["password"], securityEngineId=v2c.OctetString( hexValue=traffy_config.SWITCHES[id]["engine_id"])) ntfrcv.NotificationReceiver(snmp_engine, trap_callback) snmp_engine.transportDispatcher.jobStarted(1) try: snmp_engine.transportDispatcher.runDispatcher() except: snmp_engine.transportDispatcher.closeDispatcher()
def run(self) -> None: self.snmpEngine = engine.SnmpEngine() config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 1161)) ) config.addV1System(self.snmpEngine, 'my-area', 'public', contextName='my-context') config.addVacmUser(self.snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) snmpContext = context.SnmpContext(self.snmpEngine) class SimpleController(instrum.AbstractMibInstrumController): def readVars(self, varBinds, acInfo=(None, None)): return [(ov[0], v2c.Integer(random.uniform(120, 140))) for ov in varBinds] snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name SimpleController() # Management Instrumentation ) cmdrsp.GetCommandResponder(self.snmpEngine, snmpContext) # cmdrsp.SetCommandResponder(self.snmpEngine, snmpContext) self.snmpEngine.transportDispatcher.jobStarted(1) try: self.snmpEngine.transportDispatcher.runDispatcher() except: self.snmpEngine.transportDispatcher.closeDispatcher() raise
def __str__(self): if self._dirty: self._dirty = False ctx = self._ctx self._logMsg = '' for grouping in self.GROUPINGS: for key in grouping: if key not in ctx: continue val = ctx[key] if key in self.FORMATTERS: val = self.FORMATTERS[key](val) elif isinstance(val, int): val = str(val) else: if val: val = v2c.OctetString(val).prettyPrint() if key in self.ALIASES: key = self.ALIASES[key] self._logMsg += '%s=%s ' % (key, val or '<nil>') return self._logMsg
def _snmp_v2v3_config(self): """Configures snmp v2 and v3 user parameters.""" community_str = constants.SNMP_COMMUNITY_STR config.addV1System(self.snmp_engine, community_str, community_str) auth_priv_protocols = { 'usmHMACMD5AuthProtocol': config.usmHMACMD5AuthProtocol, 'usmHMACSHAAuthProtocol': config.usmHMACSHAAuthProtocol, 'usmAesCfb128Protocol': config.usmAesCfb128Protocol, 'usmAesCfb256Protocol': config.usmAesCfb256Protocol, 'usmAesCfb192Protocol': config.usmAesCfb192Protocol, 'usmDESPrivProtocol': config.usmDESPrivProtocol, 'usmNoAuthProtocol': config.usmNoAuthProtocol, 'usmNoPrivProtocol': config.usmNoPrivProtocol } config.addV3User(self.snmp_engine, userName=constants.SNMP_USM_USER, authKey=constants.SNMP_V3_AUTHKEY, privKey=constants.SNMP_V3_PRIVKEY, authProtocol=auth_priv_protocols.get( constants.SNMP_V3_AUTH_PROTOCOL, config.usmNoAuthProtocol), privProtocol=auth_priv_protocols.get( constants.SNMP_V3_PRIV_PROTOCOL, config.usmNoPrivProtocol), securityEngineId=v2c.OctetString( hexValue=constants.SNMP_ENGINE_ID)) return
def NativeVal2Snmp(nativeVal, snmpValueType): """ :param nativeVal: native for python values, i.e. int/float/str etc. :return: The SNMP suitable value """ if snmpValueType is None: # Try to autodetect desired SNMP value type if isinstance(nativeVal, int): result = v2c.Integer(nativeVal) elif isinstance(nativeVal, float): result = v2c.Integer(nativeVal) elif isinstance(nativeVal, str): if IsValidIpv4Address(nativeVal): result = v2c.IpAddress(nativeVal) else: result = v2c.OctetString(nativeVal) else: raise TypeError( "Unable to autodetect SNMP value type. Please supply " "the snmpValueType argument." ", ".join(list(TYPES.keys()))) else: if snmpValueType not in TYPES: raise ValueError( "'{}' is not one of the supported types: {}".format( snmpValueType, ", ".join(list(TYPES.keys())))) result = TYPES[snmpValueType](nativeVal) return result
def _add_snmp_config(self, ctxt, new_config): LOG.info("Add snmp config:%s" % new_config) storage_id = new_config.get("storage_id") version_int = self._get_snmp_version_int(ctxt, new_config.get("version")) if version_int == constants.SNMP_V2_INT or \ version_int == constants.SNMP_V1_INT: community_string = new_config.get("community_string") community_index = self._get_community_index(storage_id) config.addV1System(self.snmp_engine, community_index, community_string, contextName=community_string) else: username = new_config.get("username") engine_id = new_config.get("engine_id") auth_key = new_config.get("auth_key") auth_protocol = new_config.get("auth_protocol") privacy_key = new_config.get("privacy_key") privacy_protocol = new_config.get("privacy_protocol") if auth_key is not None: auth_key = cryptor.decode(auth_key) if privacy_key is not None: privacy_key = cryptor.decode(privacy_key) config.addV3User( self.snmp_engine, userName=username, authKey=auth_key, privKey=privacy_key, authProtocol=self._get_usm_auth_protocol(ctxt, auth_protocol), privProtocol=self._get_usm_priv_protocol(ctxt, privacy_protocol), securityEngineId=v2c.OctetString(hexValue=engine_id))
def add_user(cls, port, username, securityengineid, authkey=None, privkey=None, authProtocol=None, privProtocol=None): """ Add SNMP V3 User :param port: SNMP Trap Port :param username: SNMP User name :param securityengineid: SNMP Engine id in Hex form :param authkey: SNMP Authkey default is None :param privkey: SNMP Privkey string default is None :param authProtocol: Auth Protocol, default is None :param privProtocol: Privacy Protocol, default is None :return: Treu or False """ result = True snmpEngine = cls.get_asyncoredispatcher(port) #debug.setLogger(debug.Debug('all')) try: authprotocol = cls.authProtocol.get(authProtocol, None) privprotocol = cls.authProtocol.get(privProtocol, None) config.addV3User( snmpEngine=snmpEngine, userName=username, authProtocol = authprotocol, authKey=authkey, privProtocol = privprotocol, privKey=privkey, securityEngineId = v2c.OctetString(hexValue=securityengineid) ) except: testcase_Utils.pNote("ADD SNMPv3 User Failed", "error") result = False return result
def send_trap(self): self.generate() ntfOrg = ntforg.NotificationOriginator() ntfOrg.sendNotification( ntforg.CommunityData('public'), ntforg.UdpTransportTarget((self.cm.getTrapIp(), 5050)), 'trap', ntforg.MibVariable('SNMPv2-MIB', 'sysLocation'), ('1.3.6.1.6.3.1.1.5.4', v2c.OctetString(self.data)))
def _if_phys_addr_get(idx, nextf): r = cps_get_if(idx, nextf) if not r: return None phys_addr = cps_attr_data_get( r, 'dell-if/if/interfaces/interface/phys-address') if phys_addr is None: phys_addr = '' phys_addr = [] if phys_addr == '' else map(lambda x: int(x, 16), phys_addr.split(':')) return (cps_key_attr_data_get( r, 'dell-base-if-cmn/if/interfaces/interface/if-index'), v2c.OctetString(phys_addr))
def _delete_snmp_config(self, ctxt, snmp_config): LOG.info("Delete snmp config:%s" % snmp_config) version_int = self._get_snmp_version_int(ctxt, snmp_config.get("version")) if version_int == constants.SNMP_V3_INT: username = snmp_config.get('username') engine_id = snmp_config.get('engine_id') config.delV3User(self.snmp_engine, userName=username, securityEngineId=v2c.OctetString( hexValue=engine_id)) else: storage_id = snmp_config.get('storage_id') community_index = self._get_community_index(storage_id) config.delV1System(self.snmp_engine, community_index)
def add_snmp_v3(snmpEngine): """ TBD :param snmpEngine: :return: """ __authProtocol = { 'usmHMACMD5AuthProtocol': config.usmHMACMD5AuthProtocol, 'usmHMACSHAAuthProtocol': config.usmHMACSHAAuthProtocol, 'usmAesCfb128Protocol': config.usmAesCfb128Protocol, 'usmAesCfb256Protocol': config.usmAesCfb256Protocol, 'usmAesCfb192Protocol': config.usmAesCfb192Protocol, 'usmDESPrivProtocol': config.usmDESPrivProtocol, 'usmNoAuthProtocol': config.usmNoAuthProtocol, 'usmNoPrivProtocol': config.usmNoPrivProtocol } while 1: V3=input("Want to add New V3 User (Yes/No/n/y)?") if V3 in ["yes", "Yes", "Y", "y"]: v3_user = input("Provide V3 User Name: ") print("\n") v3_authkey = input("Provide Auth Key: ") print("\n") v3_privkey = input("Provide Priv Key: ") print("\n") authProtocol = input("Provide authProtocol: Option: [" "usmNoAuthProtocol, " "usmHMACMD5AuthProtocol, " "usmHMACSHAAuthProtocol] :") print("\n") privProtocol = input("Provide privProtocol: Option: [" "usmNoPrivProtocol, usmDESPrivProtocol, usm3DESEDEPrivProtocol, usmAesCfb128Protocol] :") print("\n") securityEngineId = input("Provide V3 security EngineId e.g. " "'800000d30300000e112245' :") print("\n") config.addV3User( snmpEngine, userName=v3_user, authKey=v3_authkey, privKey=v3_privkey, authProtocol=__authProtocol.get( authProtocol, config.usmNoAuthProtocol), privProtocol=__authProtocol.get( privProtocol,config.usmNoPrivProtocol), securityEngineId=v2c.OctetString( hexValue=securityEngineId)) elif V3 in ["No", "n", "N", "no"]: break else: continue
def _add_snmp_config(self, ctxt, new_config): storage_id = new_config.get("storage_id") LOG.info("Start to add snmp trap config for storage: %s", storage_id) try: version_int = self._get_snmp_version_int(ctxt, new_config.get("version")) if version_int == constants.SNMP_V2_INT or \ version_int == constants.SNMP_V1_INT: community_string = cryptor.decode( new_config.get("community_string")) community_string = encodeutils.to_utf8(community_string) community_index = self._get_community_index(storage_id) config.addV1System(self.snmp_engine, community_index, community_string, contextName=community_string) else: username = new_config.get("username") engine_id = new_config.get("engine_id") if engine_id: engine_id = v2c.OctetString(hexValue=engine_id) auth_key = new_config.get("auth_key") auth_protocol = new_config.get("auth_protocol") privacy_key = new_config.get("privacy_key") privacy_protocol = new_config.get("privacy_protocol") if auth_key: auth_key = encodeutils.to_utf8(cryptor.decode(auth_key)) if privacy_key: privacy_key = encodeutils.to_utf8( cryptor.decode(privacy_key)) config.addV3User( self.snmp_engine, userName=username, authKey=auth_key, privKey=privacy_key, authProtocol=self._get_usm_auth_protocol(ctxt, auth_protocol), privProtocol=self._get_usm_priv_protocol(ctxt, privacy_protocol), securityEngineId=engine_id) LOG.info("Add snmp trap config for storage: %s successfully.", storage_id) except Exception as e: msg = six.text_type(e) LOG.error("Failed to add snmp trap config for storage: %s. " "Reason: %s", storage_id, msg) raise e
def _if_phys_addr_get(idx, nextf): k = {} if idx is not None: k['dell-base-if-cmn/if/interfaces/interface/if-index'] = idx if nextf: k['cps/object-group/get-next'] = 1 r = cps_get('target', 'dell-base-if-cmn/if/interfaces/interface', k) if r is None or len(r) == 0: return None r = r[0] phys_addr = cps_attr_data_get( r, 'dell-if/if/interfaces/interface/phys-address') if phys_addr is None: phys_addr = '' phys_addr = [] if phys_addr == '' else map(lambda x: int(x, 16), phys_addr.split(':')) return (cps_key_attr_data_get( r, 'dell-base-if-cmn/if/interfaces/interface/if-index'), v2c.OctetString(phys_addr))
def _delete_snmp_config(self, ctxt, snmp_config): LOG.info("Start to remove snmp trap config.") version_int = self._get_snmp_version_int(ctxt, snmp_config.get("version")) if version_int == constants.SNMP_V3_INT: username = snmp_config.get('username') engine_id = snmp_config.get('engine_id') if engine_id: engine_id = v2c.OctetString(hexValue=engine_id) try: config.delV3User(self.snmp_engine, userName=username, securityEngineId=engine_id) except Exception as e: msg = six.text_type(e) LOG.warning("Snmp trap configuration to be " "deleted could not be found. Reason: %s", msg) else: storage_id = snmp_config.get('storage_id') community_index = self._get_community_index(storage_id) config.delV1System(self.snmp_engine, community_index)
def setMibController(snmpEngine, controller): """Register SNMP MIB instrumentation controller with SNMP engine. Args: snmpEngine (object): pysnmp `SnmpEngine` class instance controller (object): SNMP MIB instrumentation controller compliant to pysnmp MIB instrumentation API. Returns: object: pysnmp `SnmpContext` object representing SNMP context for which SNMP MIB instrumentation controller is registered. """ snmpContextName = v2c.OctetString('') # https://github.com/openstack/virtualpdu/blob/master/virtualpdu/pdu/pysnmp_handler.py snmpContext = context.SnmpContext(snmpEngine) snmpContext.unregisterContextName(snmpContextName) snmpContext.registerContextName(snmpContextName, controller) return snmpContext
def run(self): snmpEngine = engine.SnmpEngine() config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', self.__listening_port)) ) config.addV1System( snmpEngine, 'my-area', 'public', contextName='my-context') config.addVacmUser(snmpEngine=snmpEngine, securityModel=2, securityName='my-area', securityLevel='noAuthNoPriv', readSubTree=SNMPAgentResponder.OID_PREFIX, writeSubTree=(), notifySubTree=()) snmpContext = context.SnmpContext(snmpEngine) snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name self.__responder # Management Instrumentation ) cmdrsp.GetCommandResponder(snmpEngine, snmpContext) snmpEngine.transportDispatcher.jobStarted(1) self.__barrier.wait() # TODO with statement here! try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
def _setup(self, q): """Setup a new agent in a separate process. The port the agent is listening too will be returned using the provided queue. """ port = random.randrange(22000, 22989) snmpEngine = engine.SnmpEngine() if self.ipv6: config.addSocketTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', port))) else: config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', port))) # Community is public and MIB is writable config.addV1System(snmpEngine, 'read-write', 'public') config.addVacmUser(snmpEngine, 1, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addVacmUser(snmpEngine, 2, 'read-write', 'noAuthNoPriv', (1, 3, 6), (1, 3, 6)) config.addV3User(snmpEngine, 'read-write', config.usmHMACMD5AuthProtocol, 'authpass', config.usmAesCfb128Protocol, 'privpass') config.addVacmUser(snmpEngine, 3, 'read-write', 'authPriv', (1, 3, 6), (1, 3, 6)) # Build MIB def stringToOid(string): return [ord(x) for x in string] def flatten(*args): result = [] for el in args: if isinstance(el, (list, tuple)): for sub in el: result.append(sub) else: result.append(el) return tuple(result) snmpContext = context.SnmpContext(snmpEngine) mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalar, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalar', 'MibScalarInstance') mibBuilder.exportSymbols( '__MY_SNMPv2_MIB', # SNMPv2-MIB::sysDescr MibScalar((1, 3, 6, 1, 2, 1, 1, 1), v2c.OctetString()), MibScalarInstance((1, 3, 6, 1, 2, 1, 1, 1), (0, ), v2c.OctetString("Snimpy Test Agent"))) mibBuilder.exportSymbols( '__MY_IF_MIB', # IF-MIB::ifNumber MibScalar((1, 3, 6, 1, 2, 1, 2, 1), v2c.Integer()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 1), (0, ), v2c.Integer(3)), # IF-MIB::ifTable MibTable((1, 3, 6, 1, 2, 1, 2, 2)), MibTableRow((1, 3, 6, 1, 2, 1, 2, 2, 1)).setIndexNames( (0, '__MY_IF_MIB', 'ifIndex')), # IF-MIB::ifIndex MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (1, ), v2c.Integer(1)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (2, ), v2c.Integer(2)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), (3, ), v2c.Integer(3)), # IF-MIB::ifDescr MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), v2c.OctetString()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (1, ), v2c.OctetString("lo")), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (2, ), v2c.OctetString("eth0")), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), (3, ), v2c.OctetString("eth1")), # IF-MIB::ifType MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), v2c.Integer()), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (1, ), v2c.Integer(24)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (2, ), v2c.Integer(6)), MibScalarInstance((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), (3, ), v2c.Integer(6)), # IF-MIB::ifIndex ifIndex=MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), v2c.Integer())) mibBuilder.exportSymbols( '__MY_SNIMPY-MIB', # SNIMPY-MIB::snimpyIpAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 1), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 1), (0, ), v2c.OctetString("AAAA")), # SNIMPY-MIB::snimpyString MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 2), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 2), (0, ), v2c.OctetString("bye")), # SNIMPY-MIB::snimpyInteger MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 3), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 3), (0, ), v2c.Integer(19)), # SNIMPY-MIB::snimpyEnum MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 4), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 4), (0, ), v2c.Integer(2)), # SNIMPY-MIB::snimpyObjectId MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 5), v2c.ObjectIdentifier()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 5), (0, ), v2c.ObjectIdentifier((1, 3, 6, 4454, 0, 0))), # SNIMPY-MIB::snimpyBoolean MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 6), (0, ), v2c.Integer(1)), # SNIMPY-MIB::snimpyCounter MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 7), v2c.Counter32()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 7), (0, ), v2c.Counter32(47)), # SNIMPY-MIB::snimpyGauge MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 8), v2c.Gauge32()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 8), (0, ), v2c.Gauge32(18)), # SNIMPY-MIB::snimpyTimeticks MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 9), v2c.TimeTicks()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 9), (0, ), v2c.TimeTicks(12111100)), # SNIMPY-MIB::snimpyCounter64 MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 10), v2c.Counter64()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 10), (0, ), v2c.Counter64(2**48 + 3)), # SNIMPY-MIB::snimpyBits MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 11), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 11), (0, ), v2c.OctetString(b"\xa0")), # SNIMPY-MIB::snimpyMacAddress MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 15), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 15), (0, ), v2c.OctetString(b"\x11\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyMacAddressInvalid MibScalar((1, 3, 6, 1, 2, 1, 45121, 1, 16), v2c.OctetString()).setMaxAccess("readwrite"), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 1, 16), (0, ), v2c.OctetString(b"\xf1\x12\x13\x14\x15\x16")), # SNIMPY-MIB::snimpyIndexTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 3)), MibTableRow((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyIndexVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexOidVarLen"), (0, "__MY_SNIMPY-MIB", "snimpyIndexFixedLen"), (1, "__MY_SNIMPY-MIB", "snimpyIndexImplied")), # SNIMPY-MIB::snimpyIndexInt MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row1'), 3, 1, 2, 3, stringToOid('alpha5'), stringToOid('end of row1')), v2c.Integer(4571)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row2'), 4, 1, 0, 2, 3, stringToOid('beta32'), stringToOid('end of row2')), v2c.Integer(78741)), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), flatten(4, stringToOid('row3'), 4, 120, 1, 2, 3, stringToOid('gamma7'), stringToOid('end of row3')), v2c.Integer(4110)), # SNIMPY-MIB::snimpyInvalidTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 5)), MibTableRow((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyInvalidIndex")), # SNIMPY-MIB::snimpyInvalidDescr MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), (1, ), v2c.OctetString(b"Hello")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), (2, ), v2c.OctetString(b"\xf1\x12\x13\x14\x15\x16")), # Indexes snimpyIndexVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), v2c.OctetString()).setMaxAccess("noaccess"), snimpyIndexIntIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 2), v2c.Integer()).setMaxAccess("noaccess"), snimpyIndexOidVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 3), v2c.ObjectIdentifier()).setMaxAccess("noaccess"), snimpyIndexFixedLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 4), v2c.OctetString().setFixedLength(6)).setMaxAccess("noaccess"), snimpyIndexImplied=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 5), v2c.OctetString()).setMaxAccess("noaccess"), snimpyIndexInt=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 6), v2c.Integer()).setMaxAccess("readwrite"), snimpyInvalidIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 1), v2c.Integer()).setMaxAccess("noaccess"), snimpyInvalidDescr=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 5, 1, 2), v2c.OctetString()).setMaxAccess("readwrite")) # Start agent cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) q.put(port) snmpEngine.transportDispatcher.jobStarted(1) snmpEngine.transportDispatcher.runDispatcher()
MibScalarInstance) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalarInstance') RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus') mibBuilder.exportSymbols( '__MY_MIB', # table object MibTable((1, 3, 6, 6, 1)).setMaxAccess('readcreate'), # table row object, also carries references to table indices MibTableRow((1, 3, 6, 6, 1, 5)).setMaxAccess('readcreate').setIndexNames( (0, '__MY_MIB', 'myTableIndex')), # table column: value MibTableColumn((1, 3, 6, 6, 1, 5, 2), v2c.OctetString()).setMaxAccess('readcreate'), # table column: row status MibTableColumn((1, 3, 6, 6, 1, 5, 3), RowStatus()).setMaxAccess('readcreate'), # table column: index, needs to be named to refer to as index column myTableIndex=MibTableColumn((1, 3, 6, 6, 1, 5, 1), v2c.Integer()).setMaxAccess('readcreate')) # --- end of Managed Object Instance initialization ---- # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext)
def snmpv3_trap(user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, engineid='', ip='127.0.0.1', port=162): # Create SNMP engine with autogenernated engineID and pre-bound snmp_engine = engine.SnmpEngine() config.addSocketTransport(snmp_engine, udp.domainName, udp.UdpTransport().openServerMode((ip, port))) # usmHMACMD5AuthProtocol - MD5 hashing # usmHMACSHAAuthProtocol - SHA hashing # usmNoAuthProtocol - no authentication # usmDESPrivProtocol - DES encryption # usm3DESEDEPrivProtocol - triple-DES encryption # usmAesCfb128Protocol - AES encryption, 128-bit # usmAesCfb192Protocol - AES encryption, 192-bit # usmAesCfb256Protocol - AES encryption, 256-bit # usmNoPrivProtocol - no encryption # NoAuthNoPriv if hash_meth is None and cry_meth is None: hashval = config.usmNoAuthProtocol cryval = config.usmNoPrivProtocol # AuthNoPriv elif hash_meth is not None and cry_meth is None: if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return cryval = config.usmNoPrivProtocol # AuthPriv elif hash_meth is not None and cry_meth is not None: if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return if cry_meth == '3des': cryval = config.usm3DESEDEPrivProtocol elif cry_meth == 'des': cryval = config.usmDESPrivProtocol elif cry_meth == 'aes128': cryval = config.usmAesCfb128Protocol elif cry_meth == 'aes192': cryval = config.usmAesCfb192Protocol elif cry_meth == 'aes256': cryval = config.usmAesCfb256Protocol else: print('加密算法必须是3des, des, aes128, aes192 or aes256 !') return # 提供的参数不符合标准时给出提示 else: print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。') return config.addV3User(snmp_engine, user, hashval, hash_key, cryval, cry_key, contextEngineId=v2c.OctetString(hexValue=engineid)) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmp_engine, cb_fun) snmp_engine.transportDispatcher.jobStarted( 1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmp_engine.transportDispatcher.runDispatcher() except Exception: snmp_engine.transportDispatcher.closeDispatcher() raise
config.addVacmUser(snmpEngine, 3, 'usr-md5-3des', 'authPriv', (), (), (1, 3, 6)) # SNMP context snmpContext = context.SnmpContext(snmpEngine) # # Error/confirmation reciever def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' % (sendRequestHandle, errorIndication and errorIndication or 'delivered')) sendRequestHandle = ntforg.NotificationOriginator( snmpContext).sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1, 3, 6, 1, 6, 3, 1, 1, 5, 1), # ((oid, value), ... ) (((1, 3, 6, 1, 2, 1, 1, 1), v2c.OctetString('Example Notificator')), ((1, 3, 6, 1, 2, 1, 1, 5), v2c.OctetString('Notificator Example'))), cbFun) print('Notification %s scheduled to be sent' % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher()
except: return self.getSyntax().clone(0) ###OID 0.16777252.324.0 class Answer_16777252_324_attempt_count(MibScalarInstance): def getValue(self, name, idx): try: return self.getSyntax().clone( redis_store.get('Answer_16777252_324_attempt_count')) except: return self.getSyntax().clone(0) mibBuilder.exportSymbols( '__MY_MIB', MibScalar((1, 3, 6, 1, 2, 1, 1, 1), v2c.OctetString()), AIR_hss_imsi_known_check_SQL_Fail((1, 3, 6, 1, 2, 1, 1, 1), (1, 0, 0, 0), v2c.Integer32()), AIR_hss_imsi_known_check_IMSI_unattached_w_SIM( (1, 3, 6, 1, 2, 1, 1, 1), (2, 0, 0, 0), v2c.Integer32()), AIR_hss_imsi_known_check_IMSI_Blocked((1, 3, 6, 1, 2, 1, 1, 1), (3, 0, 0, 0), v2c.Integer32()), AIR_hss_get_subscriber_data_v2_v2_IMSI_Blocked( (1, 3, 6, 1, 2, 1, 1, 1), (4, 0, 0, 0), v2c.Integer32()), AIR_general((1, 3, 6, 1, 2, 1, 1, 1), (5, 0, 0, 0), v2c.Integer32()), generate_avp_count((1, 3, 6, 1, 2, 1, 1, 1), (6, 0, 0, 0), v2c.Integer32()), generate_vendor_avp((1, 3, 6, 1, 2, 1, 1, 1), (7, 0, 0, 0), v2c.Integer32()), diameter_packet_count((1, 3, 6, 1, 2, 1, 1, 1), (8, 0, 0, 0), v2c.Integer32()),
config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1') # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Create an SNMP context with default ContextEngineId (same as SNMP engine ID) snmpContext = context.SnmpContext(snmpEngine) # Create multiple independent trees of MIB managed objects (empty so far) mibTreeA = instrum.MibInstrumController(builder.MibBuilder()) mibTreeB = instrum.MibInstrumController(builder.MibBuilder()) # Register MIB trees at distinct SNMP Context names snmpContext.registerContextName(v2c.OctetString('context-a'), mibTreeA) snmpContext.registerContextName(v2c.OctetString('context-b'), mibTreeB) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher()
snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' % (sendRequestHandle, errorIndication and errorIndication or 'delivered')) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1, 3, 6, 1, 6, 3, 1, 1, 5, 1), # ( (oid, value), ... ) ( ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')), ), cbFun) print('Notifications are scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher()
# UDP over IPv4 config.addTransport(snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 162))) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes config.addV3User(snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1', securityEngineId=v2c.OctetString(hexValue='8000000001020304')) # user: usr-md5-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1', securityEngineId=v2c.OctetString(hexValue='8000000001020304')) # user: usr-sha-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 # this USM entry is configured for TRAP receiving purposes config.addV3User(snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1',
'MibScalarInstance' ) RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus') mibBuilder.exportSymbols( '__EXAMPLE-MIB', # table object exampleTable=MibTable((1, 3, 6, 6, 1)) .setMaxAccess('read-create'), # table row object, also carries references to table indices exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5)) .setMaxAccess('read-create') .setIndexNames((0, '__EXAMPLE-MIB', 'exampleTableColumn1')), # table column: string index exampleTableColumn1=MibTableColumn((1, 3, 6, 6, 1, 5, 1), v2c.OctetString()) .setMaxAccess('read-create'), # table column: string value exampleTableColumn2=MibTableColumn((1, 3, 6, 6, 1, 5, 2), v2c.OctetString()) .setMaxAccess('read-create'), # table column: integer value with default exampleTableColumn3=MibTableColumn((1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123)) .setMaxAccess('read-create'), # table column: row status exampleTableStatus=MibTableColumn((1, 3, 6, 6, 1, 5, 4), RowStatus('notExists')) .setMaxAccess('read-create') ) # --- end of custom SNMP table definition, empty table now exists --- # --- populate custom SNMP table with one row ---
# Very basic Management Instrumentation Controller without # any Managed Objects attached. It supports only GET's and # always echos request var-binds in response. class EchoMibInstrumController(instrum.AbstractMibInstrumController): def readVars(self, *varBinds, **context): cbFun = context.get('cbFun') if cbFun: cbFun([(ov[0], v2c.OctetString('You queried OID %s' % ov[0])) for ov in varBinds], **context) # Create a custom Management Instrumentation Controller and register at # SNMP Context under ContextName 'my-context' snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name EchoMibInstrumController() # Management Instrumentation ) # Register GET&SET Applications at the SNMP engine for a custom SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher()
# Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('0.0.0.0', 1161)) ) # SNMPv3/USM setup config.addV3User( snmpEngine, userConfig['DEFAULT']['SNMPUSER'], config.usmHMAC128SHA224AuthProtocol, userConfig['DEFAULT']['SNMPAUTH'], config.usmAesCfb192Protocol, userConfig['DEFAULT']['SNMPPRIV'], securityEngineId=v2c.OctetString(hexValue='0102030405060708') ) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal 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())
def readVars(self, *varBinds, **context): cbFun = context.get('cbFun') if cbFun: cbFun([(ov[0], v2c.OctetString('You queried OID %s' % ov[0])) for ov in varBinds], **context)
config.addTransport(snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161))) # SNMPv3/USM setup # user: usr-md5-none, auth: MD5, priv NONE config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1') # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Create an SNMP context with ContextEngineId = 8000000001020304 snmpContext = context.SnmpContext( snmpEngine, contextEngineId=v2c.OctetString(hexValue='8000000001020304')) # Create an [empty] set of Managed Objects (MibBuilder), pass it to # Management Instrumentation Controller and register at SNMP Context # under ContextName 'my-context' snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name instrum.MibInstrumController(builder.MibBuilder()) # Managed Objects ) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext)
def if_descr_get_next(module, name): r = if_name_get(name[-1], True) return None if r is None else result_get_next(name, (r[0], v2c.OctetString(r[1])))