def __init__(self, client_config=None): if not client_config: client_config = conpot_config # Create SNMP engine instance self.snmpEngine = engine.SnmpEngine() # user: usr-sha-aes, auth: SHA, priv AES config.addV3User( self.snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) config.addTargetParams(self.snmpEngine, 'my-creds', 'usr-sha-aes128', 'authPriv') # Setup transport endpoint and bind it with security settings yielding # a target name (choose one entry depending of the transport needed). # UDP/IPv4 config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( self.snmpEngine, 'my-router', udp.domainName, (client_config.snmp_host, client_config.snmp_port), 'my-creds' )
def __init__(self, udpIp, udpPort): # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher self.snmpEngine = engine.SnmpEngine() self.mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibPath = self.mibBuilder.getMibPath() + ('.',) self.mibBuilder.setMibPath(*mibPath) # Setup UDP over IPv4 transport endpoint config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpSocketTransport().openServerMode((udpIp, udpPort)) ) print 'Publishing readings via SNMP' print 'Agent address {}:{}'.format(udpIp, udpPort) print 'Community name public' # v1/2 setup config.addV1System(self.snmpEngine, 'test-agent', 'public') # v3 setup config.addV3User( self.snmpEngine, 'test-user' ) # VACM setup config.addContext(self.snmpEngine, '') config.addRwUser(self.snmpEngine, 1, 'test-agent', 'noAuthNoPriv', (1,3,6)) # v1 config.addRwUser(self.snmpEngine, 2, 'test-agent', 'noAuthNoPriv', (1,3,6)) # v2c config.addRwUser(self.snmpEngine, 3, 'test-user', 'noAuthNoPriv', (1,3,6)) # v3 # SNMP context snmpContext = context.SnmpContext(self.snmpEngine) # Apps registration cmdrsp.GetCommandResponder(self.snmpEngine, snmpContext) cmdrsp.SetCommandResponder(self.snmpEngine, snmpContext) cmdrsp.NextCommandResponder(self.snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(self.snmpEngine, snmpContext) MibScalarInstance, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') class ScalarFromCallback(MibScalarInstance): def __init__(self, sensorId, valueGetter, typeName, instId, syntax): MibScalarInstance.__init__(self, typeName, instId, syntax) self.valueGetter = valueGetter def readTest(self, name, val, idx, (acFun, acCtx)): if not self.valueGetter(): raise error.NoAccessError(idx=idx, name=name) def readGet(self, name, val, idx, (acFun, acCtx)): value = self.valueGetter() if not value: raise error.NoAccessError(idx=idx, name=name) else: return name, self.syntax.clone(value)
def run(self): snmpEngine = engine.SnmpEngine() if self.ipv6: domainName = udp6.domainName config.addSocketTransport(snmpEngine,domainName,udp6.Udp6Transport().openServerMode((self.host, self.port))) else: domainName = udp.domainName config.addSocketTransport(snmpEngine,domainName,udp.UdpTransport().openServerMode((self.host, self.port))) config.addV3User(snmpEngine, self.user,self.auth_proto, self.auth_key,self.priv_proto,self.priv_key) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, v3trapCallback) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: # catch *all* exceptions e = sys.exc_info()[1] snmpEngine.transportDispatcher.closeDispatcher() logging.error("Looks like an error: %s" % str(e)) sys.exit(1)
def __init__(self, objects): self._snmpEngine = engine.SnmpEngine() config.addSocketTransport( self._snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((_addr, _port))) config.addV3User(self._snmpEngine,_account,config.usmHMACMD5AuthProtocol,_auth_key,config.usmDESPrivProtocol,_priv_key) config.addVacmUser(self._snmpEngine, 3, _account, "authPriv",(1,3,6,1,4,1), (1,3,6,1,4,1)) self._snmpContext = context.SnmpContext(self._snmpEngine) #builder create mibBuilder = self._snmpContext.getMibInstrum().getMibBuilder() mibSources = mibBuilder.getMibSources() + (builder.DirMibSource('.'),)+(builder.DirMibSource(filepath),) mibBuilder.setMibSources(*mibSources) MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI','MibScalarInstance') for mibObject in objects: nextVar, = mibBuilder.importSymbols(mibObject.mibName, mibObject.objectType) instance = createVariable(MibScalarInstance, mibObject.valueGetFunc, nextVar.name, (0,), nextVar.syntax) #need to export as <var name>Instance instanceDict = {str(nextVar.name)+"Instance":instance} mibBuilder.exportSymbols(mibObject.mibName, **instanceDict) cmdrsp.GetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.SetCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.NextCommandResponder(self._snmpEngine, self._snmpContext) cmdrsp.BulkCommandResponder(self._snmpEngine, self._snmpContext)
def _add_v3_md5_des_user(self, user): """ Setup v3 user with md5, des """ config.addV3User(self.snmpEngine, user[0], config.usmHMACMD5AuthProtocol, user[1], config.usmDESPrivProtocol, user[2])
def addV3User(self, securityName, authProtocol=config.usmNoAuthProtocol, authKey=None, privProtocol=config.usmNoPrivProtocol, privKey=None, contextEngineId=None): config.addV3User(self.snmpEngine, securityName, authProtocol, authKey, privProtocol, privKey, contextEngineId) return
def cfgCmdGen(self, authData, transportTarget, tagList=''): if self.__knownAuths.has_key(authData): paramsName = self.__knownAuths[authData] else: paramsName = 'p%s' % nextID() if isinstance(authData, CommunityData): config.addV1System( self.snmpEngine, authData.securityName, authData.communityName ) config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) elif isinstance(authData, UsmUserData): config.addV3User( self.snmpEngine, authData.securityName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey ) config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel ) else: raise error.PySnmpError('Unsupported SNMP version') self.__knownAuths[authData] = paramsName if not self.__knownTransports.has_key(transportTarget.transportDomain): transport = transportTarget.openClientMode() config.addSocketTransport( self.snmpEngine, transportTarget.transportDomain, transport ) self.__knownTransports[transportTarget.transportDomain] = transport k = transportTarget, tagList if self.__knownTransportAddrs.has_key(k): addrName = self.__knownTransportAddrs[k] else: addrName = 'a%s' % nextID() config.addTargetAddr( self.snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, tagList ) self.__knownTransportAddrs[k] = addrName return addrName, paramsName
def __init__(self, host, port, rcommunity): self.snmpEngine = engine.SnmpEngine() config.addSocketTransport(self.snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((host, port))) config.addV1System(self.snmpEngine, 'my-area', rcommunity) config.addVacmUser(self.snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6)) config.addV3User(self.snmpEngine, 'test') config.addVacmUser(self.snmpEngine, 3, 'test', 'noAuthNoPriv', (1, 3, 6)) self.snmpContext = context.SnmpContext(self.snmpEngine) self.mibBuilder = self.snmpContext.getMibInstrum().getMibBuilder() self.MibScalar, self.MibScalarInstance = self.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibScalarInstance') cmdrsp.GetCommandResponder(self.snmpEngine, self.snmpContext) cmdrsp.NextCommandResponder(self.snmpEngine, self.snmpContext) cmdrsp.BulkCommandResponder(self.snmpEngine, self.snmpContext)
def _configureUsers(self, snmpEngine, snmpContext, params): logger.debug ( 'Configure users' ); for user in params.users: logger.debug ( 'Creating user "%s"', user.name ); # Parse authentication algorithm authAlgo = config.usmNoAuthProtocol; if user.authAlgo is not None: if not user.authAlgo in self.authAlgorithms: msg = 'Invalid snmp V3 Authentification algorithm %s. Valid values are: %s' % (user.authAlgo, self.authAlgorithms.keys()) logger.error ( msg ); raise ClusterException(msg); else: authAlgo = self.authAlgorithms[user.authAlgo.lower()]; # Parse privacy algorithm privAlgo = config.usmNoPrivProtocol; if user.privAlgo is not None: if not user.privAlgo in self.privAlgorithms: msg = 'Invalid snmp V3 Privacy algorithm %s. Valid values are: %s' % (user.privAlgo, self.privAlgorithms.keys()) logger.error ( msg ); raise ClusterException(msg); else: privAlgo = self.privAlgorithms[user.privAlgo.lower()]; # Check provided parameters if authAlgo==config.usmNoAuthProtocol and privAlgo!=config.usmNoPrivProtocol: msg = 'Privacy impossible without authentication for user: %s' % (user.name) logger.error ( msg ); raise ClusterException(msg); if authAlgo!=config.usmNoAuthProtocol and user.authPass is None: msg = 'No authentication password given for user %s' % (user.name) logger.error ( msg ); raise ClusterException(msg); if privAlgo!=config.usmNoPrivProtocol and user.privPass is None: msg = 'No privacy password given for user %s' % (user.name) logger.error ( msg ); raise ClusterException(msg); # At least we can create the user config.addV3User( snmpEngine, user.name, authAlgo, user.authPass, privAlgo, user.privPass ) pass; pass;
def v3TargetName( self, engine, ip, port=161, authKey=None, privKey=None, authProtocol='MD5', privProtocol='DES', ): """Find/create target name for v1/v2 connection to given agent authProtocol -- one of None, 'MD5' or 'SHA' determining the hashing of the authorisation key (password) privProtocol -- one of None or 'DES', determining encryption of the messages sent to the agent authKey -- authorisation key (password) for the agent privKey -- key used to obscure requests from eavesdroppers """ if authKey is None: authProtocol = None if privKey is None: privProtocol = None authProtocol = self.AUTH_PROTOCOL_REGISTRY[ authProtocol ] privProtocol = self.PRIV_PROTOCOL_REGISTRY[ privProtocol ] key = ( authProtocol, authKey, privProtocol, privKey ) paramName = self._v3paramCache.get( key ) if paramName is None: nameID = self._newV3Name() name = 'v3user-%s'%(nameID) config.addV3User( engine, name, authProtocol=authProtocol, authKey=authKey, privProtocol=privProtocol, privKey=privKey ) if authProtocol is config.usmNoAuthProtocol: paramType = "noAuthNoPriv" elif privProtocol is config.usmNoPrivProtocol: paramType = "authNoPriv" else: paramType = "authPriv" paramName = 'v3param-%s'%(nameID) config.addTargetParams( engine, paramName, name, paramType, mpModel = 3 ) self._v3paramCache[ key ] = paramName return self._targetName( engine, ip, port, paramName )
def __init__(self): self.snmpEngine = engine.SnmpEngine() config.addSocketTransport( self.snmpEngine, udp.domainName, udp.UdpSocketTransport().openServerMode(('0.0.0.0', 162)) ) config.addV1System(self.snmpEngine, 'test-agent', 'public') config.addV3User( self.snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # '80004fb81c3dafe69' # ContextEngineID of Notification Originator ) # Apps registration ntfrcv.NotificationReceiver(self.snmpEngine, self.recvcallback) self.snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish self.snmpEngine.transportDispatcher.runDispatcher()
def __init__(self, host, port, username, password, snmp_context): self.snmp_context = snmp_context self.snmp_engine = engine.SnmpEngine() # HiT7300 uses the user password for encryption (privacy protocol) pass phrase (PSK?) config.addV3User( self.snmp_engine, username, config.usmHMACMD5AuthProtocol, password, config.usmAesCfb128Protocol, password ) # pysnmp bug? # setting context doesn't affect the getCommandGenerator, so we don't set it # FIXME: report upstream and have cmdgen use context of snmpEngine!? # config.addContext(self.snmp_engine, 'tnms') # snmp_context = context.SnmpContext(self.snmp_engine) config.addTargetParams(self.snmp_engine, "myParams", username, "authPriv") # config.addTargetParams(self.snmp_engine, 'myParams', username, 'authPriv') config.addTargetAddr(self.snmp_engine, "myTarget", config.snmpUDPDomain, (host, int(port)), "myParams") config.addSocketTransport(self.snmp_engine, udp.domainName, udp.UdpSocketTransport().openClientMode()) self.cbCtx = {}
def __init__(self, host, port, log_queue): self.log_queue = log_queue # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # Transport setup udp_sock = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM) udp_sock.setsockopt(gevent.socket.SOL_SOCKET, gevent.socket.SO_BROADCAST, 1) udp_sock.bind((host, port)) # UDP over IPv4 self.addSocketTransport( self.snmpEngine, udp.domainName, udp_sock ) #SNMPv1 config.addV1System(self.snmpEngine, 'public-read', 'public') # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( self.snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( self.snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES/128 config.addV3User( self.snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(self.snmpEngine, 1, 'public-read', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(self.snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(self.snmpEngine, snmpContext) cmdrsp.SetCommandResponder(self.snmpEngine, snmpContext) cmdrsp.NextCommandResponder(self.snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(self.snmpEngine, snmpContext)
# Create and put on-line my managed object sysDescr, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr') MibScalarInstance, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') sysDescrInstance = MibScalarInstance( sysDescr.name, (0,), sysDescr.syntax.clone('Example Command Responder') ) snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.exportSymbols('PYSNMP-EXAMPLE-MIB', sysDescrInstance) # add anonymous Managed Object Instance # v1/2 setup config.addV1System(snmpEngine, 'test-agent', 'public') # v3 setup config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # config.usmAesCfb128Protocol, 'privkey1' ) # Install default Agent configuration #config.setInitialVacmParameters(snmpEngine) # # Apply initial VACM configuration to this user #config.addVacmGroup(snmpEngine, "initial", 3, "test-user") # Alternatively, configure VACM from the scratch config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'test-agent', 'noAuthNoPriv', (1,3,6), (1,3,6)) # v1 config.addVacmUser(snmpEngine, 2, 'test-agent', 'noAuthNoPriv', (1,3,6), (1,3,6)) # v2c
def do_run(self): ''' Run sensor. ''' # Too many branches. # pylint: disable=R0912 from pysnmp.error import PySnmpError from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntfrcv from pysnmp.proto.api import v2c # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher. snmp_engine = engine.SnmpEngine() # Transport setup. try: socket.inet_pton(socket.AF_INET, self.config['interface_ip']) # UDP over IPv4. config.addSocketTransport( snmp_engine, udp.domainName, udp.UdpTransport().openServerMode( (self.config['interface_ip'], self.config['port']) ) ) except socket.error: try: socket.inet_pton(socket.AF_INET6, self.config['interface_ip']) # UDP over IPv6. config.addSocketTransport( snmp_engine, udp6.domainName, udp6.Udp6Transport().openServerMode( (self.config['interface_ip'], self.config['port']) ) ) except socket.error: self.log('given interface_ip is neither IPv4 nor IPv6 address') return snmpv3_protocols = { 'MD5': config.usmHMACMD5AuthProtocol, 'SHA': config.usmHMACSHAAuthProtocol, 'DES': config.usmDESPrivProtocol, '3DES': config.usm3DESEDEPrivProtocol, 'AES128': config.usmAesCfb128Protocol, 'AES192': config.usmAesCfb192Protocol, 'AES256': config.usmAesCfb256Protocol } def snmpv3_setup_args(version, authentication=None, encryption=None, auth_key=None, encrypt_key=None, device_id=None): ''' Helper function, parses args. ''' # R0913: Too many arguments # pylint: disable=R0913 del version del device_id args = [snmp_engine, 'usr-{}-{}'.format( authentication.lower() if authentication else 'none', encryption.lower() if encryption else 'none' )] if authentication: # Expression not assigned # pylint: disable=W0106 args.append(snmpv3_protocols[authentication]), args.append(auth_key) if encryption: # Expression not assigned # pylint: disable=W0106 args.append(snmpv3_protocols[encryption]), args.append(encrypt_key) return args # Setup devices. for device in self.config['devices']: if device['version'] == 'v3': # SNMPv3 setup. if 'device_id' in device: config.addV3User( *snmpv3_setup_args(**device), contextEngineId=v2c.OctetString(hexValue=device['device_id']) ) else: config.addV3User(*snmpv3_setup_args(**device)) else: # SNMPv1/2c setup. # SecurityName <-> CommunityName mapping. config.addV1System( snmp_engine, device['index'], device['name'] ) def cb_fun(snmp_engine, state_reference, context_engine_id, context_name, var_binds, cb_ctx): # Too many arguments # pylint: disable=R0913 ''' Callback function for receiving notifications. ''' _, transport_address = snmp_engine.msgAndPduDsp.getTransportInfo( state_reference ) for name, val in var_binds: self.send_results(datetime.utcnow(), ( ('sender', transport_address), ('context_engine_id', context_engine_id.prettyPrint()), ('context_name', context_name.prettyPrint()), ('variable_name', name.prettyPrint()), ('variable_value', val.prettyPrint()) )) # Register SNMP Application at the SNMP engine. ntfrcv.NotificationReceiver(snmp_engine, cb_fun) # This job would never finish. snmp_engine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send confirmations. try: snmp_engine.transportDispatcher.runDispatcher() except PySnmpError as err: snmp_engine.transportDispatcher.closeDispatcher() self.send_results(datetime.utcnow(), (('error', err.message),)) return
# $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 -E 80004fb805636c6f75644dab22cc -n da761cfc8c94d3aceef4f60f049105ba -ObentU 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-md5-none, auth: MD5, priv: NONE config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1') config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport(snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()) config.addTargetAddr(snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds') # Error/response receiver
# Notification originator from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context from pysnmp.proto.api import v2c snmpEngine = engine.SnmpEngine() # v1/2 setup config.addV1System(snmpEngine, 'test-agent', 'public') # v3 setup config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Transport params config.addTargetParams(snmpEngine, 'myParams', 'test-user', 'authPriv') #config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 0) # Transport addresses config.addTargetAddr( snmpEngine, 'myNMS', config.snmpUDPDomain, ('127.0.0.1', 162), 'myParams', tagList='myManagementStations' ) # Notification targets config.addNotificationTarget( # snmpEngine, 'myNotifyName', 'myParams', 'myManagementStations', 'trap'
def cfgCmdGen(self, authData, transportTarget, tagList=null): if authData not in self.__knownAuths: if isinstance(authData, CommunityData): config.addV1System( self.snmpEngine, authData.securityName, authData.communityName, authData.contextEngineId, authData.contextName, tagList ) elif isinstance(authData, UsmUserData): config.addV3User( self.snmpEngine, authData.securityName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.contextEngineId ) else: raise error.PySnmpError('Unsupported authentication object') self.__knownAuths[authData] = 1 k = authData.securityName, authData.securityLevel, authData.mpModel if k in self.__knownParams: paramsName = self.__knownParams[k] else: paramsName = 'p%s' % nextID() config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) self.__knownParams[k] = paramsName if transportTarget.transportDomain not in self.__knownTransports: transport = transportTarget.openClientMode() config.addSocketTransport( self.snmpEngine, transportTarget.transportDomain, transport ) self.__knownTransports[transportTarget.transportDomain] = transport k = paramsName, transportTarget, tagList if k in self.__knownTransportAddrs: addrName = self.__knownTransportAddrs[k] else: addrName = 'a%s' % nextID() config.addTargetAddr( self.snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, tagList ) self.__knownTransportAddrs[k] = addrName return addrName, paramsName
def snmpv3_trap(user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, engineid=''): #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 hashval = None cryval = None #NoAuthNoPriv if hash_meth == None and cry_meth == None: hashval = config.usmNoAuthProtocol cryval = config.usmNoPrivProtocol #AuthNoPriv elif hash_meth != None and cry_meth == 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 != None and cry_meth != 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 # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES, contextEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User(snmpEngine, user, hashval, hash_key, cryval, cry_key, contextEngineId=v2c.OctetString(hexValue=engineid)) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
snmpEngine, unix.domainName, unix.UnixTransport().openServerMode('/tmp/snmp-agent')) # # SNMPv1/2c setup (if you need to handle SNMPv1/v2c messages) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # SNMPv3/USM setup (if you need to handle SNMPv3 messages) # # user: usr-md5-des, auth: MD5, priv DES config.addV3User(snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1') # user: usr-none-none, auth: NONE, priv NONE config.addV3User(snmpEngine, 'usr-none-none') # user: usr-md5-none, auth: MD5, priv NONE config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1') # user: usr-sha-aes128, auth: SHA, priv AES config.addV3User(snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1') # user: usr-md5-aes256, auth: MD5, priv AES256 config.addV3User(snmpEngine, 'usr-md5-aes256', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmAesCfb256Protocol, 'privkey1')
from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport(snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(('127.0.0.1', 161))) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User(snmpEngine, 'usr-md5-des', config.USM_AUTH_HMAC96_MD5, 'authkey1', config.USM_PRIV_CBC56_DES, 'privkey1') # user: usr-sha-none, auth: SHA, priv NONE config.addV3User(snmpEngine, 'usr-sha-none', config.USM_AUTH_HMAC96_SHA, 'authkey1') # user: usr-sha-none, auth: SHA, priv AES config.addV3User(snmpEngine, 'usr-sha-aes128', config.USM_AUTH_HMAC96_SHA, 'authkey1', config.USM_PRIV_CFB128_AES, 'privkey1') # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv',
def main(): class CommandResponder(cmdrsp.CommandResponderBase): pduTypes = (rfc1905.SetRequestPDU.tagSet, rfc1905.GetRequestPDU.tagSet, rfc1905.GetNextRequestPDU.tagSet, rfc1905.GetBulkRequestPDU.tagSet) def handleMgmtOperation(self, snmpEngine, stateReference, contextName, pdu, acInfo): trunkReq = gCurrentRequestContext.copy() trunkReq['snmp-pdu'] = pdu pluginIdList = trunkReq['plugins-list'] logCtx = LogString(trunkReq) reqCtx = {} for pluginNum, pluginId in enumerate(pluginIdList): st, pdu = pluginManager.processCommandRequest( pluginId, snmpEngine, pdu, trunkReq, reqCtx) if st == status.BREAK: log.debug('plugin %s inhibits other plugins' % pluginId, ctx=logCtx) pluginIdList = pluginIdList[:pluginNum] break elif st == status.DROP: log.debug( 'received SNMP message, plugin %s muted request' % pluginId, ctx=logCtx) self.releaseStateInformation(stateReference) return elif st == status.RESPOND: log.debug( 'received SNMP message, plugin %s forced immediate response' % pluginId, ctx=logCtx) try: self.sendPdu(snmpEngine, stateReference, pdu) except PySnmpError: log.error('failure sending SNMP response', ctx=logCtx) else: self.releaseStateInformation(stateReference) return # pass query to trunk trunkIdList = trunkReq['trunk-id-list'] if trunkIdList is None: log.error('no route configured', ctx=logCtx) self.releaseStateInformation(stateReference) return for trunkId in trunkIdList: cbCtx = pluginIdList, trunkId, trunkReq, snmpEngine, stateReference, reqCtx try: msgId = trunkingManager.sendReq(trunkId, trunkReq, self.trunkCbFun, cbCtx) except SnmpfwdError: log.error( 'received SNMP message, message not sent to trunk "%s"' % sys.exc_info()[1], ctx=logCtx) return log.debug( 'received SNMP message, forwarded as trunk message #%s' % msgId, ctx=logCtx) def trunkCbFun(self, msgId, trunkRsp, cbCtx): pluginIdList, trunkId, trunkReq, snmpEngine, stateReference, reqCtx = cbCtx for key in tuple(trunkRsp): if key != 'callflow-id': trunkRsp['client-' + key] = trunkRsp[key] del trunkRsp[key] trunkRsp['callflow-id'] = trunkReq['callflow-id'] logCtx = LogString(trunkRsp) if trunkRsp['client-error-indication']: log.info( 'received trunk message #%s, remote end reported error-indication "%s", NOT responding' % (msgId, trunkRsp['client-error-indication']), ctx=logCtx) elif 'client-snmp-pdu' not in trunkRsp: log.info( 'received trunk message #%s, remote end does not send SNMP PDU, NOT responding' % msgId, ctx=logCtx) else: pdu = trunkRsp['client-snmp-pdu'] for pluginId in pluginIdList: st, pdu = pluginManager.processCommandResponse( pluginId, snmpEngine, pdu, trunkReq, reqCtx) if st == status.BREAK: log.debug('plugin %s inhibits other plugins' % pluginId, ctx=logCtx) break elif st == status.DROP: log.debug('plugin %s muted response' % pluginId, ctx=logCtx) self.releaseStateInformation(stateReference) return try: self.sendPdu(snmpEngine, stateReference, pdu) except PySnmpError: log.error('failure sending SNMP response', ctx=logCtx) else: log.debug( 'received trunk message #%s, forwarded as SNMP message' % msgId, ctx=logCtx) self.releaseStateInformation(stateReference) # # SNMPv3 NotificationReceiver implementation # class NotificationReceiver(ntfrcv.NotificationReceiver): pduTypes = (rfc1157.TrapPDU.tagSet, rfc1905.SNMPv2TrapPDU.tagSet) def processPdu(self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, maxSizeResponseScopedPDU, stateReference): trunkReq = gCurrentRequestContext.copy() if messageProcessingModel == 0: pdu = rfc2576.v1ToV2(pdu) # TODO: why this is not automatic? v2c.apiTrapPDU.setDefaults(pdu) trunkReq['snmp-pdu'] = pdu pluginIdList = trunkReq['plugins-list'] logCtx = LogString(trunkReq) reqCtx = {} for pluginNum, pluginId in enumerate(pluginIdList): st, pdu = pluginManager.processNotificationRequest( pluginId, snmpEngine, pdu, trunkReq, reqCtx) if st == status.BREAK: log.debug('plugin %s inhibits other plugins' % pluginId, ctx=logCtx) pluginIdList = pluginIdList[:pluginNum] break elif st == status.DROP: log.debug('plugin %s muted request' % pluginId, ctx=logCtx) return elif st == status.RESPOND: log.debug('plugin %s NOT forced immediate response' % pluginId, ctx=logCtx) # TODO: implement immediate response for confirmed-class PDU return # pass query to trunk trunkIdList = trunkReq['trunk-id-list'] if trunkIdList is None: log.error('no route configured', ctx=logCtx) return for trunkId in trunkIdList: # TODO: pass messageProcessingModel to respond cbCtx = pluginIdList, trunkId, trunkReq, snmpEngine, stateReference, reqCtx try: msgId = trunkingManager.sendReq(trunkId, trunkReq, self.trunkCbFun, cbCtx) except SnmpfwdError: log.error( 'received SNMP message, message not sent to trunk "%s" %s' % (trunkId, sys.exc_info()[1]), ctx=logCtx) return log.debug( 'received SNMP message, forwarded as trunk message #%s' % msgId, ctx=logCtx) def trunkCbFun(self, msgId, trunkRsp, cbCtx): pluginIdList, trunkId, trunkReq, snmpEngine, stateReference, reqCtx = cbCtx for key in tuple(trunkRsp): if key != 'callflow-id': trunkRsp['client-' + key] = trunkRsp[key] del trunkRsp[key] trunkRsp['callflow-id'] = trunkReq['callflow-id'] logCtx = LazyLogString(trunkReq, trunkRsp) if trunkRsp['client-error-indication']: log.info( 'received trunk message #%s, remote end reported error-indication "%s", NOT responding' % (msgId, trunkRsp['client-error-indication']), ctx=logCtx) else: if 'client-snmp-pdu' not in trunkRsp: log.debug( 'received trunk message #%s -- unconfirmed SNMP message' % msgId, ctx=logCtx) return pdu = trunkRsp['client-snmp-pdu'] for pluginId in pluginIdList: st, pdu = pluginManager.processNotificationResponse( pluginId, snmpEngine, pdu, trunkReq, reqCtx) if st == status.BREAK: log.debug('plugin %s inhibits other plugins' % pluginId, ctx=logCtx) break elif st == status.DROP: log.debug( 'received trunk message #%s, plugin %s muted response' % (msgId, pluginId), ctx=logCtx) return log.debug( 'received trunk message #%s, forwarded as SNMP message' % msgId, ctx=logCtx) # TODO: implement response part # # Agent-side API complies with SMIv2 # if messageProcessingModel == 0: # PDU = rfc2576.v2ToV1(PDU, origPdu) # # statusInformation = {} # # # 3.4.3 # try: # snmpEngine.msgAndPduDsp.returnResponsePdu( # snmpEngine, messageProcessingModel, securityModel, # securityName, securityLevel, contextEngineId, # contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU, # stateReference, statusInformation) # # except error.StatusInformation: # log.error('processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) class LogString(LazyLogString): GROUPINGS = [ ['callflow-id'], [ 'snmp-engine-id', 'snmp-transport-domain', 'snmp-bind-address', 'snmp-bind-port', 'snmp-security-model', 'snmp-security-level', 'snmp-security-name', 'snmp-credentials-id' ], ['snmp-context-engine-id', 'snmp-context-name', 'snmp-context-id'], ['snmp-pdu', 'snmp-content-id'], ['snmp-peer-address', 'snmp-peer-port', 'snmp-peer-id'], ['trunk-id'], ['client-snmp-pdu'], ] FORMATTERS = { 'client-snmp-pdu': LazyLogString.prettyVarBinds, 'snmp-pdu': LazyLogString.prettyVarBinds, } def securityAuditObserver(snmpEngine, execpoint, variables, cbCtx): securityModel = variables.get('securityModel', 0) logMsg = 'SNMPv%s auth failure' % securityModel logMsg += ' at %s:%s' % variables['transportAddress'].getLocalAddress() logMsg += ' from %s:%s' % variables['transportAddress'] statusInformation = variables.get('statusInformation', {}) if securityModel in (1, 2): logMsg += ' using snmp-community-name "%s"' % statusInformation.get( 'communityName', '?') elif securityModel == 3: logMsg += ' using snmp-usm-user "%s"' % statusInformation.get( 'msgUserName', '?') try: logMsg += ': %s' % statusInformation['errorIndication'] except KeyError: pass log.error(logMsg) def requestObserver(snmpEngine, execpoint, variables, cbCtx): trunkReq = { 'callflow-id': '%10.10x' % random.randint(0, 0xffffffffff), 'snmp-engine-id': snmpEngine.snmpEngineID, 'snmp-transport-domain': variables['transportDomain'], 'snmp-peer-address': variables['transportAddress'][0], 'snmp-peer-port': variables['transportAddress'][1], 'snmp-bind-address': variables['transportAddress'].getLocalAddress()[0], 'snmp-bind-port': variables['transportAddress'].getLocalAddress()[1], 'snmp-security-model': variables['securityModel'], 'snmp-security-level': variables['securityLevel'], 'snmp-security-name': variables['securityName'], 'snmp-context-engine-id': variables['contextEngineId'], 'snmp-context-name': variables['contextName'], } trunkReq['snmp-credentials-id'] = macro.expandMacro( credIdMap.get( (str(snmpEngine.snmpEngineID), variables['transportDomain'], variables['securityModel'], variables['securityLevel'], str(variables['securityName']))), trunkReq) k = '#'.join([ str(x) for x in (variables['contextEngineId'], variables['contextName']) ]) for x, y in contextIdList: if y.match(k): trunkReq['snmp-context-id'] = macro.expandMacro(x, trunkReq) break else: trunkReq['snmp-context-id'] = None addr = '%s:%s#%s:%s' % ( variables['transportAddress'][0], variables['transportAddress'][1], variables['transportAddress'].getLocalAddress()[0], variables['transportAddress'].getLocalAddress()[1]) for pat, peerId in peerIdMap.get(str(variables['transportDomain']), ()): if pat.match(addr): trunkReq['snmp-peer-id'] = macro.expandMacro(peerId, trunkReq) break else: trunkReq['snmp-peer-id'] = None pdu = variables['pdu'] if pdu.tagSet == v1.TrapPDU.tagSet: pdu = rfc2576.v1ToV2(pdu) v2c.apiTrapPDU.setDefaults(pdu) k = '#'.join([ snmpPduTypesMap.get(variables['pdu'].tagSet, '?'), '|'.join([str(x[0]) for x in v2c.apiTrapPDU.getVarBinds(pdu)]) ]) for x, y in contentIdList: if y.match(k): trunkReq['snmp-content-id'] = macro.expandMacro(x, trunkReq) break else: trunkReq['snmp-content-id'] = None trunkReq['plugins-list'] = pluginIdMap.get( (trunkReq['snmp-credentials-id'], trunkReq['snmp-context-id'], trunkReq['snmp-peer-id'], trunkReq['snmp-content-id']), []) trunkReq['trunk-id-list'] = trunkIdMap.get( (trunkReq['snmp-credentials-id'], trunkReq['snmp-context-id'], trunkReq['snmp-peer-id'], trunkReq['snmp-content-id'])) cbCtx.clear() cbCtx.update(trunkReq) # # main script starts here # helpMessage = """\ Usage: %s [--help] [--version ] [--debug-snmp=<%s>] [--debug-asn1=<%s>] [--daemonize] [--process-user=<uname>] [--process-group=<gname>] [--pid-file=<file>] [--logging-method=<%s[:args>]>] [--log-level=<%s>] [--config-file=<file>]""" % (sys.argv[0], '|'.join([ x for x in pysnmp_debug.flagMap.keys() if x != 'mibview' ]), '|'.join([x for x in pyasn1_debug.flagMap.keys()]), '|'.join( log.methodsMap.keys()), '|'.join(log.levelsMap)) try: opts, params = getopt.getopt(sys.argv[1:], 'hv', [ 'help', 'version', 'debug=', 'debug-snmp=', 'debug-asn1=', 'daemonize', 'process-user='******'process-group=', 'pid-file=', 'logging-method=', 'log-level=', 'config-file=' ]) except Exception: sys.stderr.write('ERROR: %s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage)) return if params: sys.stderr.write('ERROR: extra arguments supplied %s\r\n%s\r\n' % (params, helpMessage)) return pidFile = '' cfgFile = CONFIG_FILE foregroundFlag = True procUser = procGroup = None loggingMethod = ['stderr'] loggingLevel = None for opt in opts: if opt[0] == '-h' or opt[0] == '--help': sys.stderr.write("""\ Synopsis: SNMP Proxy Forwarder: server part. Receives SNMP requests at one or many built-in SNMP Agents and routes them to encrypted trunks established with Forwarder's Manager part(s) running elsewhere. Can implement complex routing logic through analyzing parts of SNMP messages and matching them against proxying rules. Documentation: http://snmpfwd.sourceforge.io/ %s """ % helpMessage) return if opt[0] == '-v' or opt[0] == '--version': import snmpfwd import pysnmp import pyasn1 sys.stderr.write("""\ SNMP Proxy Forwarder version %s, written by Ilya Etingof <*****@*****.**> Using foundation libraries: pysnmp %s, pyasn1 %s. Python interpreter: %s Software documentation and support at https://github.com/etingof/snmpfwd %s """ % (snmpfwd.__version__, hasattr(pysnmp, '__version__') and pysnmp.__version__ or 'unknown', hasattr(pyasn1, '__version__') and pyasn1.__version__ or 'unknown', sys.version, helpMessage)) return elif opt[0] == '--debug-snmp': pysnmp_debug.setLogger( pysnmp_debug.Debug(*opt[1].split(','), **dict(loggerName=PROGRAM_NAME + '.pysnmp'))) elif opt[0] == '--debug-asn1': pyasn1_debug.setLogger( pyasn1_debug.Debug(*opt[1].split(','), **dict(loggerName=PROGRAM_NAME + '.pyasn1'))) elif opt[0] == '--daemonize': foregroundFlag = False elif opt[0] == '--process-user': procUser = opt[1] elif opt[0] == '--process-group': procGroup = opt[1] elif opt[0] == '--pid-file': pidFile = opt[1] elif opt[0] == '--logging-method': loggingMethod = opt[1].split(':') elif opt[0] == '--log-level': loggingLevel = opt[1] elif opt[0] == '--config-file': cfgFile = opt[1] try: log.setLogger(PROGRAM_NAME, *loggingMethod, **dict(force=True)) if loggingLevel: log.setLevel(loggingLevel) except SnmpfwdError: sys.stderr.write('%s\r\n%s\r\n' % (sys.exc_info()[1], helpMessage)) return try: cfgTree = cparser.Config().load(cfgFile) except SnmpfwdError: log.error('configuration parsing error: %s' % sys.exc_info()[1]) return if cfgTree.getAttrValue('program-name', '', default=None) != PROGRAM_NAME: log.error('config file %s does not match program name %s' % (cfgFile, PROGRAM_NAME)) return if cfgTree.getAttrValue('config-version', '', default=None) != CONFIG_VERSION: log.error( 'config file %s version is not compatible with program version %s' % (cfgFile, CONFIG_VERSION)) return random.seed() gCurrentRequestContext = {} credIdMap = {} peerIdMap = {} contextIdList = [] contentIdList = [] pluginIdMap = {} trunkIdMap = {} engineIdMap = {} transportDispatcher = AsynsockDispatcher() transportDispatcher.registerRoutingCbFun(lambda td, t, d: td) transportDispatcher.setSocketMap() # use global asyncore socket map # # Initialize plugin modules # pluginManager = PluginManager(macro.expandMacros( cfgTree.getAttrValue('plugin-modules-path-list', '', default=[], vector=True), {'config-dir': os.path.dirname(cfgFile)}), progId=PROGRAM_NAME, apiVer=PLUGIN_API_VERSION) for pluginCfgPath in cfgTree.getPathsToAttr('plugin-id'): pluginId = cfgTree.getAttrValue('plugin-id', *pluginCfgPath) pluginMod = cfgTree.getAttrValue('plugin-module', *pluginCfgPath) pluginOptions = macro.expandMacros( cfgTree.getAttrValue('plugin-options', *pluginCfgPath, **dict(default=[], vector=True)), {'config-dir': os.path.dirname(cfgFile)}) log.info( 'configuring plugin ID %s (at %s) from module %s with options %s...' % (pluginId, '.'.join(pluginCfgPath), pluginMod, ', '.join(pluginOptions) or '<none>')) try: pluginManager.loadPlugin(pluginId, pluginMod, pluginOptions) except SnmpfwdError: log.error('plugin %s not loaded: %s' % (pluginId, sys.exc_info()[1])) return for configEntryPath in cfgTree.getPathsToAttr('snmp-credentials-id'): credId = cfgTree.getAttrValue('snmp-credentials-id', *configEntryPath) configKey = [] log.info('configuring snmp-credentials %s (at %s)...' % (credId, '.'.join(configEntryPath))) engineId = cfgTree.getAttrValue('snmp-engine-id', *configEntryPath) if engineId in engineIdMap: snmpEngine, snmpContext, snmpEngineMap = engineIdMap[engineId] log.info('using engine-id %s' % snmpEngine.snmpEngineID.prettyPrint()) else: snmpEngine = engine.SnmpEngine(snmpEngineID=engineId) snmpContext = context.SnmpContext(snmpEngine) snmpEngineMap = {'transportDomain': {}, 'securityName': {}} snmpEngine.observer.registerObserver( securityAuditObserver, 'rfc2576.prepareDataElements:sm-failure', 'rfc3412.prepareDataElements:sm-failure', cbCtx=gCurrentRequestContext) snmpEngine.observer.registerObserver( requestObserver, 'rfc3412.receiveMessage:request', cbCtx=gCurrentRequestContext) CommandResponder(snmpEngine, snmpContext) NotificationReceiver(snmpEngine, None) engineIdMap[engineId] = snmpEngine, snmpContext, snmpEngineMap log.info('new engine-id %s' % snmpEngine.snmpEngineID.prettyPrint()) configKey.append(str(snmpEngine.snmpEngineID)) transportDomain = cfgTree.getAttrValue('snmp-transport-domain', *configEntryPath) transportDomain = rfc1902.ObjectName(transportDomain) if transportDomain in snmpEngineMap['transportDomain']: h, p, transportDomain = snmpEngineMap['transportDomain'][ transportDomain] log.info('using transport endpoint %s:%s, transport ID %s' % (h, p, transportDomain)) else: if transportDomain[:len(udp.domainName)] == udp.domainName: transport = udp.UdpTransport() elif transportDomain[:len(udp6.domainName)] == udp6.domainName: transport = udp6.Udp6Transport() else: log.error('unknown transport domain %s' % (transportDomain, )) return h, p = cfgTree.getAttrValue('snmp-bind-address', *configEntryPath).split(':', 1) snmpEngine.registerTransportDispatcher(transportDispatcher, transportDomain) transportOptions = cfgTree.getAttrValue( 'snmp-transport-options', *configEntryPath, **dict(default=[], vector=True)) t = transport.openServerMode((h, int(p))) if 'transparent-proxy' in transportOptions: t.enablePktInfo() t.enableTransparent() elif 'virtual-interface' in transportOptions: t.enablePktInfo() config.addSocketTransport(snmpEngine, transportDomain, t) snmpEngineMap['transportDomain'][ transportDomain] = h, p, transportDomain log.info( 'new transport endpoint %s:%s, options %s, transport ID %s' % (h, p, transportOptions and '/'.join(transportOptions) or '<none>', transportDomain)) configKey.append(transportDomain) securityModel = cfgTree.getAttrValue('snmp-security-model', *configEntryPath) securityModel = rfc1902.Integer(securityModel) securityLevel = cfgTree.getAttrValue('snmp-security-level', *configEntryPath) securityLevel = rfc1902.Integer(securityLevel) securityName = cfgTree.getAttrValue('snmp-security-name', *configEntryPath) if securityModel in (1, 2): if securityName in snmpEngineMap['securityName']: if snmpEngineMap['securityName'][ securityModel] == securityModel: log.info('using security-name %s' % securityName) else: raise SnmpfwdError( 'snmp-security-name %s already in use at snmp-security-model %s' % (securityName, securityModel)) else: communityName = cfgTree.getAttrValue('snmp-community-name', *configEntryPath) config.addV1System(snmpEngine, securityName, communityName, securityName=securityName) log.info( 'new community-name %s, security-model %s, security-name %s, security-level %s' % (communityName, securityModel, securityName, securityLevel)) snmpEngineMap['securityName'][securityName] = securityModel configKey.append(securityModel) configKey.append(securityLevel) configKey.append(securityName) elif securityModel == 3: if securityName in snmpEngineMap['securityName']: log.info('using USM security-name: %s' % securityName) else: usmUser = cfgTree.getAttrValue('snmp-usm-user', *configEntryPath) log.info( 'new USM user %s, security-model %s, security-level %s, security-name %s' % (usmUser, securityModel, securityLevel, securityName)) if securityLevel in (2, 3): usmAuthProto = cfgTree.getAttrValue( 'snmp-usm-auth-protocol', *configEntryPath, **dict(default=config.usmHMACMD5AuthProtocol)) usmAuthProto = rfc1902.ObjectName(usmAuthProto) usmAuthKey = cfgTree.getAttrValue('snmp-usm-auth-key', *configEntryPath) log.info( 'new USM authentication key: %s, authentication protocol: %s' % (usmAuthKey, usmAuthProto)) if securityLevel == 3: usmPrivProto = cfgTree.getAttrValue( 'snmp-usm-priv-protocol', *configEntryPath, **dict(default=config.usmDESPrivProtocol)) usmPrivProto = rfc1902.ObjectName(usmPrivProto) usmPrivKey = cfgTree.getAttrValue( 'snmp-usm-priv-key', *configEntryPath, **dict(default=None)) log.info( 'new USM encryption key: %s, encryption protocol: %s' % (usmPrivKey, usmPrivProto)) config.addV3User(snmpEngine, usmUser, usmAuthProto, usmAuthKey, usmPrivProto, usmPrivKey) else: config.addV3User(snmpEngine, usmUser, usmAuthProto, usmAuthKey) else: config.addV3User(snmpEngine, usmUser) snmpEngineMap['securityName'][securityName] = securityModel configKey.append(securityModel) configKey.append(securityLevel) configKey.append(securityName) else: raise SnmpfwdError('unknown snmp-security-model: %s' % securityModel) configKey = tuple(configKey) if configKey in credIdMap: log.error( 'ambiguous configuration for key snmp-credentials-id=%s at %s' % (credId, '.'.join(configEntryPath))) return credIdMap[configKey] = credId duplicates = {} for peerCfgPath in cfgTree.getPathsToAttr('snmp-peer-id'): peerId = cfgTree.getAttrValue('snmp-peer-id', *peerCfgPath) if peerId in duplicates: log.error( 'duplicate snmp-peer-id=%s at %s and %s' % (peerId, '.'.join(peerCfgPath), '.'.join(duplicates[peerId]))) return duplicates[peerId] = peerCfgPath log.info('configuring peer ID %s (at %s)...' % (peerId, '.'.join(peerCfgPath))) transportDomain = cfgTree.getAttrValue('snmp-transport-domain', *peerCfgPath) if transportDomain not in peerIdMap: peerIdMap[transportDomain] = [] for peerAddress in cfgTree.getAttrValue( 'snmp-peer-address-pattern-list', *peerCfgPath, **dict(vector=True)): for bindAddress in cfgTree.getAttrValue( 'snmp-bind-address-pattern-list', *peerCfgPath, **dict(vector=True)): peerIdMap[transportDomain].append( (re.compile(peerAddress + '#' + bindAddress), peerId)) duplicates = {} for contextCfgPath in cfgTree.getPathsToAttr('snmp-context-id'): contextId = cfgTree.getAttrValue('snmp-context-id', *contextCfgPath) if contextId in duplicates: log.error('duplicate snmp-context-id=%s at %s and %s' % (contextId, '.'.join(contextCfgPath), '.'.join( duplicates[contextId]))) return duplicates[contextId] = contextCfgPath k = '#'.join((cfgTree.getAttrValue('snmp-context-engine-id-pattern', *contextCfgPath), cfgTree.getAttrValue('snmp-context-name-pattern', *contextCfgPath))) log.info('configuring context ID %s (at %s), composite key: %s' % (contextId, '.'.join(contextCfgPath), k)) contextIdList.append((contextId, re.compile(k))) duplicates = {} for contentCfgPath in cfgTree.getPathsToAttr('snmp-content-id'): contentId = cfgTree.getAttrValue('snmp-content-id', *contentCfgPath) if contentId in duplicates: log.error('duplicate snmp-content-id=%s at %s and %s' % (contentId, '.'.join(contentCfgPath), '.'.join( duplicates[contentId]))) return duplicates[contentId] = contentCfgPath for x in cfgTree.getAttrValue('snmp-pdu-oid-prefix-pattern-list', *contentCfgPath, **dict(vector=True)): k = '#'.join([ cfgTree.getAttrValue('snmp-pdu-type-pattern', *contentCfgPath), x ]) log.info('configuring content ID %s (at %s), composite key: %s' % (contentId, '.'.join(contentCfgPath), k)) contentIdList.append((contentId, re.compile(k))) del duplicates for pluginCfgPath in cfgTree.getPathsToAttr('using-plugin-id-list'): pluginIdList = cfgTree.getAttrValue('using-plugin-id-list', *pluginCfgPath, **dict(vector=True)) log.info('configuring plugin ID(s) %s (at %s)...' % (','.join(pluginIdList), '.'.join(pluginCfgPath))) for credId in cfgTree.getAttrValue('matching-snmp-credentials-id-list', *pluginCfgPath, **dict(vector=True)): for peerId in cfgTree.getAttrValue('matching-snmp-peer-id-list', *pluginCfgPath, **dict(vector=True)): for contextId in cfgTree.getAttrValue( 'matching-snmp-context-id-list', *pluginCfgPath, **dict(vector=True)): for contentId in cfgTree.getAttrValue( 'matching-snmp-content-id-list', *pluginCfgPath, **dict(vector=True)): k = credId, contextId, peerId, contentId if k in pluginIdMap: log.error( 'duplicate snmp-credentials-id %s, snmp-context-id %s, snmp-peer-id %s, snmp-content-id %s at plugin-id(s) %s' % (credId, contextId, peerId, contentId, ','.join(pluginIdList))) return else: log.info( 'configuring plugin(s) %s (at %s), composite key: %s' % (','.join(pluginIdList), '.'.join(pluginCfgPath), '/'.join(k))) for pluginId in pluginIdList: if not pluginManager.hasPlugin(pluginId): log.error( 'undefined plugin ID %s referenced at %s' % (pluginId, '.'.join(pluginCfgPath))) return pluginIdMap[k] = pluginIdList for routeCfgPath in cfgTree.getPathsToAttr('using-trunk-id-list'): trunkIdList = cfgTree.getAttrValue('using-trunk-id-list', *routeCfgPath, **dict(vector=True)) log.info('configuring destination trunk ID(s) %s (at %s)...' % (','.join(trunkIdList), '.'.join(routeCfgPath))) for credId in cfgTree.getAttrValue('matching-snmp-credentials-id-list', *routeCfgPath, **dict(vector=True)): for peerId in cfgTree.getAttrValue('matching-snmp-peer-id-list', *routeCfgPath, **dict(vector=True)): for contextId in cfgTree.getAttrValue( 'matching-snmp-context-id-list', *routeCfgPath, **dict(vector=True)): for contentId in cfgTree.getAttrValue( 'matching-snmp-content-id-list', *routeCfgPath, **dict(vector=True)): k = credId, contextId, peerId, contentId if k in trunkIdMap: log.error( 'duplicate snmp-credentials-id %s, snmp-context-id %s, snmp-peer-id %s, snmp-content-id %s at trunk-id(s) %s' % (credId, contextId, peerId, contentId, ','.join(trunkIdList))) return else: trunkIdMap[k] = trunkIdList log.info( 'configuring trunk routing to %s (at %s), composite key: %s' % (','.join(trunkIdList), '.'.join(routeCfgPath), '/'.join(k))) def dataCbFun(trunkId, msgId, msg): log.debug('message ID %s received from trunk %s' % (msgId, trunkId)) trunkingManager = TrunkingManager(dataCbFun) def getTrunkAddr(a, port=0): f = lambda h, p=port: (h, int(p)) try: return f(*a.split(':')) except Exception: raise SnmpfwdError('improper IPv4 endpoint %s' % a) for trunkCfgPath in cfgTree.getPathsToAttr('trunk-id'): trunkId = cfgTree.getAttrValue('trunk-id', *trunkCfgPath) secret = cfgTree.getAttrValue('trunk-crypto-key', *trunkCfgPath, **dict(default='')) secret = secret and (secret * ((16 // len(secret)) + 1))[:16] log.info('configuring trunk ID %s (at %s)...' % (trunkId, '.'.join(trunkCfgPath))) connectionMode = cfgTree.getAttrValue('trunk-connection-mode', *trunkCfgPath) if connectionMode == 'client': trunkingManager.addClient( trunkId, getTrunkAddr( cfgTree.getAttrValue('trunk-bind-address', *trunkCfgPath)), getTrunkAddr( cfgTree.getAttrValue('trunk-peer-address', *trunkCfgPath), 30201), cfgTree.getAttrValue('trunk-ping-period', *trunkCfgPath, default=0, expect=int), secret) log.info( 'new trunking client from %s to %s' % (cfgTree.getAttrValue('trunk-bind-address', *trunkCfgPath), cfgTree.getAttrValue('trunk-peer-address', *trunkCfgPath))) if connectionMode == 'server': trunkingManager.addServer( getTrunkAddr( cfgTree.getAttrValue('trunk-bind-address', *trunkCfgPath), 30201), cfgTree.getAttrValue('trunk-ping-period', *trunkCfgPath, default=0, expect=int), secret) log.info( 'new trunking server at %s' % (cfgTree.getAttrValue('trunk-bind-address', *trunkCfgPath))) transportDispatcher.registerTimerCbFun(trunkingManager.setupTrunks, random.randrange(1, 5)) transportDispatcher.registerTimerCbFun(trunkingManager.monitorTrunks, random.randrange(1, 5)) try: daemon.dropPrivileges(procUser, procGroup) except Exception: log.error('can not drop privileges: %s' % sys.exc_info()[1]) return if not foregroundFlag: try: daemon.daemonize(pidFile) except Exception: log.error('can not daemonize process: %s' % sys.exc_info()[1]) return # Run mainloop log.info('starting I/O engine...') transportDispatcher.jobStarted(1) # server job would never finish # Python 2.4 does not support the "finally" clause while True: try: transportDispatcher.runDispatcher() except (PySnmpError, SnmpfwdError, socket.error): log.error(str(sys.exc_info()[1])) continue except Exception: transportDispatcher.closeDispatcher() raise
def start_listener(self, callback, address=None, port=1162, community='public', timeout=TIMEOUT): ''' Start a TRAP v1/v2c/v3 notification receiver with predefined users. @param callback: Takes these args snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx @param address: The address to listen to @param port: The port to listen to @param community: The community name for v2c Predefined users: usr-md5-des usr-md5-none usr-sha-aes128 Auth: authkey1 Priv: privkey1 ''' if not address: address = get_local_ip(self.host) if timeout < 0: timeout = 10**10 # Create SNMP engine with auto-generated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup if IPAddress(address).version == 4: # UDP over IPv4 domain_oid = udp.domainName transport = udp.UdpTransport() else: # UDP over IPv6 domain_oid = udp6.domainName transport = udp6.Udp6Transport() # Waiting up to TIMEOUT seconds for the port to be released LOG.debug('Waiting for port %s:%d to become available...', address, port) transport = wait(lambda: transport.openServerMode((address, port)), timeout=TIMEOUT, interval=1) LOG.info('Listening for traps on %s:%d...', address, port) config.addSocketTransport(snmpEngine, domain_oid, transport) # Terrible monkey patching!! # But there's no other way to cause the dispatcher loop to end if we # don't get what we expect in a given amount of time. For now that time # is limited to TIMEOUT seconds. end = time.time() + timeout def jobsArePending(self): if self._AbstractTransportDispatcher__jobs and time.time() < end: return 1 else: return 0 snmpEngine.transportDispatcher.__class__.jobsArePending = jobsArePending # SNMPv1/2 setup config.addV1System(snmpEngine, 'test-agent', community) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User(snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1') # user: usr-md5-des, auth: MD5, priv DES, contextEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1', contextEngineId=v2c.OctetString(hexValue='8000000001020304')) # user: usr-md5-none, auth: MD5, priv NONE config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1') # user: usr-md5-none, auth: MD5, priv NONE, contextEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1', contextEngineId=v2c.OctetString(hexValue='8000000001020304')) # user: usr-sha-aes128, auth: SHA, priv AES config.addV3User(snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1') # user: usr-sha-aes128, auth: SHA, priv AES, contextEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1', contextEngineId=v2c.OctetString(hexValue='8000000001020304')) # def sample_callback(snmpEngine, stateReference, contextEngineId, contextName, # varBinds, cbCtx): # print('Notification received, ContextEngineId "%s", ContextName "%s"' % ( # contextEngineId.prettyPrint(), contextName.prettyPrint()) # ) # for name, val in varBinds: # print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # print # If callback() returns True we'll stop the loop def callback_wrapper(*args, **kwargs): if callback(*args, **kwargs): snmpEngine.transportDispatcher.jobFinished(DEFAULT_JOB) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, callback_wrapper) #return address, port t = TrapListener(snmpEngine) t.start() return address, port, t
# Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Setup transport endpoint config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openServerMode(('127.0.0.1', 162))) # v1/2 setup config.addV1System(snmpEngine, 'test-agent', 'public') # v3 setup config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # '\x80\x00\x4f\xb8\x1c\x3d\xaf\xe6' # ContextEngineID of # Notification Originator ) # Callback function for receiving notifications def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo( stateReference) print 'Notification from %s, SNMP Engine \"%s\", Context \"%s\"' % ( transportAddress, contextEngineId, contextName) for name, val in varBinds: print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
def sendTrap(self, version, enterprise, varList, community=False, destPort=False): if destPort: trapPort = destPort else: trapPort = TRAP_PORT if community: comm = community else: comm = DEFAULT_COMM snmpEngine = engine.SnmpEngine() # v1/2 setup config.addV1System(snmpEngine, TEST_AGENT, comm) # v3 setup config.addV3User(snmpEngine, TEST_USER, config.usmHMACMD5AuthProtocol, 'authKey1', config.usmDESPrivProtocol, 'privKey1') # Transport params config.addTargetParams(snmpEngine, PARAM, TEST_USER, AUTHPRIV) #config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 0) # Transport addresses config.addTargetAddr(snmpEngine, NMS, config.snmpUDPDomain, (self.dataCollector, trapPort), PARAM, tagList='myManagementStations') # Notification targets config.addNotificationTarget( # snmpEngine, 'myNotifyName', 'myParams', 'myManagementStations', 'trap' snmpEngine, 'myNotifyName', PARAM, 'myManagementStations', 'inform') # Setup transport endpoint config.addSocketTransport(snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode()) # Agent-side VACM setup config.addContext(snmpEngine, '') config.addTrapUser(snmpEngine, 1, 'test-agent', 'noAuthNoPriv', (1, 3, 6)) # v1 config.addTrapUser(snmpEngine, 2, 'test-agent', 'noAuthNoPriv', (1, 3, 6)) # v2c config.addTrapUser(snmpEngine, 3, 'test-user', 'authPriv', (1, 3, 6)) # v3 # SNMP context snmpContext = context.SnmpContext(snmpEngine) def cbFun(sendRequestHandle, errorIndication, cbCtx): if errorIndication: print errorIndication ntforg.NotificationOriginator(snmpContext).sendNotification( snmpEngine, 'myNotifyName', ('SNMPv2-MIB', 'coldStart'), (((1, 3, 6, 1, 2, 1, 1, 5), v2c.OctetString('Example Notificator')), ), cbFun) snmpEngine.transportDispatcher.runDispatcher()
# Setup transport endpoint config.addSocketTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openServerMode(('127.0.0.1', 162)) ) # v1/2 setup config.addV1System(snmpEngine, 'test-agent', 'public') # v3 setup config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' # '\x80\x00\x4f\xb8\x1c\x3d\xaf\xe6' # ContextEngineID of # Notification Originator ) # Callback function for receiving notifications def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) print 'Notification from %s, SNMP Engine \"%s\", Context \"%s\"' % ( transportAddress, contextEngineId, contextName ) for name, val in varBinds:
# UDP over IPv4 config.addTransport( snmpEngine, udp.DOMAIN_NAME + (2,), udp.UdpTransport().openClientMode() ) # # SNMPv3/USM setup (Agent role) # # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.USM_AUTH_HMAC96_MD5, 'authkey1', config.USM_PRIV_CBC56_DES, 'privkey1' ) # # SNMPv1/2c setup (Manager role) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1)
def snmpv3_set(ip='', user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, oid='', customer_string=''): # 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 # 添加目标,'yourDevice'(OID与处理方法),'my-creds'(用户,密码,安全模型),目的IP与端口号 config.addTargetAddr(snmpEngine, 'yourDevice', udp.domainName, (ip, 161), 'my-creds') # ========================下面的操作在判断安全模型========================== # NoAuthNoPriv if hash_meth is None and cry_meth is None: hashval = config.usmNoAuthProtocol # 配置HASH算法 cryval = config.usmNoPrivProtocol # 配置加密算法 model = 'noAuthNoPriv' # 配置安全模式 # AuthNoPriv elif hash_meth is not None and cry_meth is None: # 配置HASH算法 if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return cryval = config.usmNoPrivProtocol # 配置加密算法 model = 'authNoPriv' # 配置安全模式 # AuthPriv elif hash_meth is not None and cry_meth is not None: # 配置HASH算法 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 model = 'authPriv' # 配置安全模式 # 提供的参数不符合标准时给出提示 else: print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。') return # ========================判断安全模型结束========================== # 添加用户与他的密钥 config.addV3User(snmpEngine, user, hashval, hash_key, cryval, cry_key) config.addTargetParams(snmpEngine, 'my-creds', user, model) # 创建'my-creds',里边有用户和安全模型 # Prepare and send a request message # 创建'yourDevice',有OID和处理方法cbFun if isinstance(customer_string, str): set_value = rfc1902.OctetString(customer_string) elif isinstance(customer_string, int): set_value = rfc1902.Integer(customer_string) cmdgen.SetCommandGenerator().sendReq(snmpEngine, 'yourDevice', ((oid, set_value),), cb_fun) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() # 运行实例
def __init__(self, host, port, mibpaths): self.oid_mapping = {} self.databus_mediator = DatabusMediator(self.oid_mapping) # mapping between OID and databus keys # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # path to custom mibs mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibSources = mibBuilder.getMibSources() for mibpath in mibpaths: mibSources += (builder.DirMibSource(mibpath),) mibBuilder.setMibSources(*mibSources) # Transport setup udp_sock = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM) udp_sock.setsockopt(gevent.socket.SOL_SOCKET, gevent.socket.SO_BROADCAST, 1) udp_sock.bind((host, port)) self.server_port = udp_sock.getsockname()[1] # UDP over IPv4 self.addSocketTransport( self.snmpEngine, udp.domainName, udp_sock ) # SNMPv1 config.addV1System(self.snmpEngine, 'public-read', 'public') # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( self.snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( self.snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES/128 config.addV3User( self.snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(self.snmpEngine, 1, 'public-read', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 2, 'public-read', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-md5-des', 'authPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-none', 'authNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-aes128', 'authPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(self.snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context self.resp_app_get = conpot_cmdrsp.c_GetCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port) self.resp_app_set = conpot_cmdrsp.c_SetCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port) self.resp_app_next = conpot_cmdrsp.c_NextCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port) self.resp_app_bulk = conpot_cmdrsp.c_BulkCommandResponder(self.snmpEngine, snmpContext, self.databus_mediator, host, port)
from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1902 from pysnmp.carrier.twisted.dgram import udp # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-none, auth: SHA, priv none config.addV3User( snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-none', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) config.addTargetAddr(
snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(('127.0.0.1', 1161)) ) # SNMPv3/USM setup # user: usr-md5-none, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.USM_AUTH_HMAC96_MD5, '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(
def snmpv3_set(ip='', user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, oid='', customerString=''): #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 hashval = None cryval = None model = None config.addTargetAddr(snmpEngine, 'yourDevice', udp.domainName, (ip, 161), 'my-creds') #NoAuthNoPriv if hash_meth == None and cry_meth == None: hashval = config.usmNoAuthProtocol cryval = config.usmNoPrivProtocol model = 'noAuthNoPriv' #AuthNoPriv elif hash_meth != None and cry_meth == None: if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return cryval = config.usmNoPrivProtocol model = 'authNoPriv' #AuthPriv elif hash_meth != None and cry_meth != 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 model = 'authPriv' #提供的参数不符合标准时给出提示 else: print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。') return config.addV3User(snmpEngine, user, hashval, hash_key, cryval, cry_key) config.addTargetParams(snmpEngine, 'my-creds', user, model) # Prepare and send a request message cmdgen.SetCommandGenerator().sendReq( snmpEngine, 'yourDevice', ((oid, rfc1902.OctetString(customerString)), ), #oid与要设置的值 cbFun) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher()
# SNMP configuration snmpEngine = engine.SnmpEngine() if snmpVersion == 3: if v3PrivKey is None and v3AuthKey is None: secLevel = 'noAuthNoPriv' elif v3PrivKey is None: secLevel = 'authNoPriv' else: secLevel = 'authPriv' config.addV3User(snmpEngine, v3User, AUTH_PROTOCOLS[v3AuthProto], v3AuthKey, PRIV_PROTOCOLS[v3PrivProto], v3PrivKey) log.info( 'SNMP version 3, Context EngineID: %s Context name: %s, SecurityName: %s, ' 'SecurityLevel: %s, Authentication key/protocol: %s/%s, Encryption ' '(privacy) key/protocol: ' '%s/%s' % (v3ContextEngineId and v3ContextEngineId.prettyPrint() or '<default>', v3Context and v3Context.prettyPrint() or '<default>', v3User, secLevel, v3AuthKey is None and '<NONE>' or v3AuthKey, v3AuthProto, v3PrivKey is None and '<NONE>' or v3PrivKey, v3PrivProto)) else: v3User = '******' secLevel = 'noAuthNoPriv'
snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-none-none, auth: NONE, priv NONE config.addV3User( snmpEngine, 'usr-none-none' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # 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 readMibObjects(self, *varBinds, **context): cbFun = context.get('cbFun')
def configure(self, snmpEngine, authData, transportTarget, contextName, **options): cache = self._getCache(snmpEngine) if isinstance(authData, CommunityData): if authData.communityIndex not in cache['auth']: config.addV1System(snmpEngine, authData.communityIndex, authData.communityName, authData.contextEngineId, authData.contextName, authData.tag, authData.securityName) cache['auth'][authData.communityIndex] = authData elif isinstance(authData, UsmUserData): authDataKey = authData.userName, authData.securityEngineId if authDataKey not in cache['auth']: config.addV3User(snmpEngine, authData.userName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.securityEngineId, securityName=authData.securityName) cache['auth'][authDataKey] = authData else: raise error.PySnmpError('Unsupported authentication object') paramsKey = (authData.securityName, authData.securityLevel, authData.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] cache['parm'][paramsKey] = paramsName, useCount + 1 else: paramsName = 'p%s' % self.nextID() config.addTargetParams(snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel) cache['parm'][paramsKey] = paramsName, 1 if transportTarget.transportDomain in cache['tran']: transport, useCount = cache['tran'][ transportTarget.transportDomain] transportTarget.verifyDispatcherCompatibility(snmpEngine) cache['tran'][ transportTarget.transportDomain] = transport, useCount + 1 elif config.getTransport(snmpEngine, transportTarget.transportDomain): transportTarget.verifyDispatcherCompatibility(snmpEngine) else: transport = transportTarget.openClientMode() config.addTransport(snmpEngine, transportTarget.transportDomain, transport) cache['tran'][transportTarget.transportDomain] = transport, 1 transportKey = (paramsName, transportTarget.transportDomain, transportTarget.transportAddr, transportTarget.timeout, transportTarget.retries, transportTarget.tagList, transportTarget.iface) if transportKey in cache['addr']: addrName, useCount = cache['addr'][transportKey] cache['addr'][transportKey] = addrName, useCount + 1 else: addrName = 'a%s' % self.nextID() config.addTargetAddr(snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, transportTarget.tagList) cache['addr'][transportKey] = addrName, 1 return addrName, paramsName
Functionally similar to: | $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = 'system name' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Add USM user config.addV3User(snmpEngine, 'usr-md5-none', config.USM_AUTH_HMAC96_MD5, 'authkey1') config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport(snmpEngine, udp.DOMAIN_NAME, udp.UdpSocketTransport().openClientMode()) config.addTargetAddr(snmpEngine, 'my-nms', udp.DOMAIN_NAME, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers') # Specify what kind of notification should be sent (TRAP or INFORM),
# Register SNMP Engine object with transport dispatcher. Request incoming # data from specific transport endpoint to be funneled to this SNMP Engine. snmpEngine.registerTransportDispatcher(transportDispatcher, transportDomain) # Transport setup # UDP over IPv4 config.addTransport(snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress)) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User(snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # 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
# $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.carrier.twisted.dgram import udp # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-aes, auth: SHA, priv AES config.addV3User(snmpEngine, 'usr-sha-aes', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1') config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport(snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode()) config.addTargetAddr(snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds') # Error/response receiver
"""# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-none, auth: SHA, priv none config.addV3User( snmpEngine, 'usr-sha-none', config.USM_AUTH_HMAC96_SHA, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-none', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.DOMAIN_NAME, udp.UdpSocketTransport().openClientMode() )
snmpEngine.observer.registerObserver(requestObserver, 'rfc3412.receiveMessage:request', 'rfc3412.returnResponsePdu') # Transport setup # UDP over IPv4 config.addTransport(snmpEngine, udp.DOMAIN_NAME, udp.UdpTransport().openServerMode(('127.0.0.1', 161))) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User(snmpEngine, 'usr-md5-des', config.USM_AUTH_HMAC96_MD5, 'authkey1', config.USM_PRIV_CBC56_DES, 'privkey1') # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # 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
def snmpv3_getbulk(ip='',user='',hash_meth=None,hash_key=None,cry_meth=None,cry_key=None,oid='',num=10): #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 global maxRepetitions maxRepetitions = num hashval = None cryval = None model = None config.addTargetAddr(#添加目标,'yourDevice'(OID与处理方法),'my-creds'(用户,密码,安全模型),目的IP与端口号 snmpEngine, 'yourDevice', udp.domainName, (ip, 161), 'my-creds' ) #========================下面的操作在判断安全模型========================== #NoAuthNoPriv if hash_meth == None and cry_meth == None: hashval = config.usmNoAuthProtocol cryval = config.usmNoPrivProtocol model = 'noAuthNoPriv' #AuthNoPriv elif hash_meth != None and cry_meth == None: if hash_meth == 'md5': hashval = config.usmHMACMD5AuthProtocol elif hash_meth == 'sha': hashval = config.usmHMACSHAAuthProtocol else: print('哈希算法必须是md5 or sha!') return cryval = config.usmNoPrivProtocol model = 'authNoPriv' #AuthPriv elif hash_meth != None and cry_meth != 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 model = 'authPriv' #提供的参数不符合标准时给出提示 else: print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。') return #========================判断安全模型结束========================== config.addV3User(#添加用户与他的密钥 snmpEngine, user, hashval, hash_key, cryval, cry_key ) config.addTargetParams(snmpEngine, 'my-creds', user, model)#创建'my-creds',里边有用户和安全模型 # Prepare initial request to be sent cmdgen.BulkCommandGenerator().sendReq(snmpEngine,'yourDevice', 0, 1,((oid, None),),cbFun)#创建'yourDevice',有OID和处理方法cbFun # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher()#运行实例 return oid_list#返回oid_list
def _setup(self, q, port): """Setup a new agent in a separate process. The port the agent is listening too will be returned using the provided queue. """ 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', self.community) 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, self.authpass, config.usmAesCfb128Protocol, self.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') class RandomMibScalarInstance(MibScalarInstance): previous_value = 0 def getValue(self, name, idx): self.previous_value += random.randint(1, 2000) return self.getSyntax().clone(self.previous_value) 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 {0}".format( self.community)))) 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::ifInOctets MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 10), v2c.Integer()), RandomMibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 10), (1,), v2c.Gauge32()), RandomMibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 10), (2,), v2c.Gauge32()), RandomMibScalarInstance( (1, 3, 6, 1, 2, 1, 2, 2, 1, 10), (3,), v2c.Gauge32()), # IF-MIB::ifIndex ifIndex=MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), v2c.Integer())) args = ( '__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::snimpyIndexVarLen MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), flatten(4, stringToOid('row1'), 3, 1, 2, 3, stringToOid('alpha5'), stringToOid('end of row1')), v2c.OctetString(b"row1")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), flatten(4, stringToOid('row2'), 4, 1, 0, 2, 3, stringToOid('beta32'), stringToOid('end of row2')), v2c.OctetString(b"row2")), MibScalarInstance((1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), flatten(4, stringToOid('row3'), 4, 120, 1, 2, 3, stringToOid('gamma7'), stringToOid('end of row3')), v2c.OctetString(b"row3")), # 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"))) if self.emptyTable: args += ( # SNIMPY-MIB::snimpyEmptyTable MibTable((1, 3, 6, 1, 2, 1, 45121, 2, 6)), MibTableRow( (1, 3, 6, 1, 2, 1, 45121, 2, 6, 1)).setIndexNames( (0, "__MY_SNIMPY-MIB", "snimpyEmptyIndex"))) kwargs = dict( # Indexes snimpyIndexVarLen=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 3, 1, 1), v2c.OctetString( )), 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") ) if self.emptyTable: kwargs.update(dict( snimpyEmptyIndex=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 6, 1, 1), v2c.Integer()).setMaxAccess("noaccess"), snimpyEmptyDescr=MibTableColumn( (1, 3, 6, 1, 2, 1, 45121, 2, 6, 1, 2), v2c.OctetString()).setMaxAccess("readwrite"))) mibBuilder.exportSymbols(*args, **kwargs) # 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()
def setUsmUser(snmpEngine, security, user, authKey=None, authProtocol=None, privKey=None, privProtocol=None): """Configure SNMP v3 USM user credentials and VACM access. Args: snmpEngine (object): pysnmp `SnmpEngine` class instance security (str): SNMP security name. Used in SNMP engine configuration primarily as an ID for the given SNMP v3 authentication information. user (str): SNMP v3 USM user name authKey (str): SNMP v3 USM authentication key. Must be 8+ characters long, unless no SNMP message authentication is in use. Defaults to `None`. authProtocol (str): Authentication protocol to use. Known values are: 'MD5', 'SHA', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'NONE'. Defaults to 'NONE'. privKey (str): SNMP v3 USM privacy key. Must be 8+ characters long, unless no SNMP payload encryption is in use. Defaults to `None`. privProtocol (str): SNMP message encryption protocol to use. Known values are: 'DES', '3DES', 'AES', 'AES128', 'AES192', 'AES192BLMT', 'AES256', 'AES256BLMT', 'NONE'. Defaults to 'NONE'. Returns: str: effective SNMP authentication and privacy level. Known values are: 'noAuthNoPriv', 'authNoPriv', 'authPriv'. """ if not authKey: authProtocol = 'NONE' elif not authProtocol: authProtocol = 'MD5' if not privKey: privProtocol = 'NONE' elif not privProtocol: privProtocol = 'DES' authProtocol = AUTH_PROTOCOLS[authProtocol.upper()] privProtocol = PRIV_PROTOCOLS[privProtocol.upper()] if (authProtocol == config.usmNoAuthProtocol and privProtocol != config.usmNoPrivProtocol): raise error.BdsError('SNMP privacy implies enabled authentication') elif (authProtocol == config.usmNoAuthProtocol and privProtocol == config.usmNoPrivProtocol): authLevel = 'noAuthNoPriv' elif privProtocol != config.usmNoPrivProtocol: authLevel = 'authPriv' else: authLevel = 'authNoPriv' config.addV3User( snmpEngine, user, authProtocol, authKey, privProtocol, privKey, securityName=security) config.addVacmUser( snmpEngine, 3, security, authLevel, (1, 3, 6), (1, 3, 6), (1, 3, 6)) return authLevel
def setup_access(self): auth_mapping = {enums.AuthProtocol.MD5: config.usmHMACMD5AuthProtocol, enums.AuthProtocol.SHA: config.usmHMACSHAAuthProtocol, None: config.usmNoAuthProtocol} priv_mapping = {enums.PrivProtocol.DES: config.usmDESPrivProtocol, enums.PrivProtocol.AES: config.usmAesCfb128Protocol, None: config.usmNoPrivProtocol} if len(self.access_config.items()) == 0: raise snmp_ex.NoUserExistsError( 'No v2 community or v3 user exists') for name, obj in self.access_config.items(): if obj.mode == enums.UserVersion.V3: try: if obj.priv_protocol is None: config.addV3User(self.engine, name, auth_mapping[obj.auth_protocol], obj.auth_key.raw) LOG.info( 'Succeed to add v3 user: {} for engine: {}, ' 'auth protocol: {}, ' 'priv protocol: {}'.format(name, self.engine_id, obj.auth_protocol, None)) else: config.addV3User(self.engine, name, auth_mapping[obj.auth_protocol], obj.auth_key.raw, priv_mapping[obj.priv_protocol], obj.priv_key.raw) LOG.info( 'Succeed to add v3 user: {} for engine: {}, ' 'auth protocol: {}, ' 'priv protocol: {}'.format(name, self.engine_id, obj.auth_protocol, obj.priv_protocol)) config.addVacmUser(self.engine, 3, name, obj.security_level.index, READ_SUB_TREE, WRITE_SUB_TREE) except smi_ex.WrongValueError: LOG.exception( 'Failed to add v3 user: {} for engine: {}, ' 'auth protocol: {}, ' 'priv protocol: {}'.format(name, self.engine_id, obj.auth_protocol, None)) else: security_level = enums.SecurityLevel.NO_AUTH_NO_PRIV.index try: config.addV1System(self.engine, name, obj.community) config.addVacmUser(self.engine, 2, name, security_level, READ_SUB_TREE, WRITE_SUB_TREE) LOG.info('Succeed to add v2 user: {} for engine: {}, ' 'community: {}'.format(name, self.engine_id, obj.community)) except smi_ex.WrongValueError: LOG.exception('Failed to add v2 user: {} for engine: {}, ' 'community: {}'.format(name, self.engine_id, obj.community))
# Transport setup # 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 config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used 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 config.addV3User( snmpEngine, 'usr-md5-none',
Functionally similar to: | $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = 'system name' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Add USM user config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers'
"""# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-aes, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes', config.USM_AUTH_HMAC96_SHA, 'authkey1', config.USM_PRIV_CFB128_AES, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.DOMAIN_NAME, udp.UdpSocketTransport().openClientMode()
def configure(self, snmpEngine, authData, transportTarget, *options): cache = self._getCache(snmpEngine) if isinstance(authData, CommunityData): if authData.communityIndex not in cache['auth']: config.addV1System( snmpEngine, authData.communityIndex, authData.communityName, authData.contextEngineId, authData.contextName, authData.tag, authData.securityName ) cache['auth'][authData.communityIndex] = authData elif isinstance(authData, UsmUserData): authDataKey = authData.userName, authData.securityEngineId if authDataKey not in cache['auth']: config.addV3User( snmpEngine, authData.userName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.securityEngineId, securityName=authData.securityName ) cache['auth'][authDataKey] = authData else: raise error.PySnmpError('Unsupported authentication object') paramsKey = (authData.securityName, authData.securityLevel, authData.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] cache['parm'][paramsKey] = paramsName, useCount + 1 else: paramsName = 'p%s' % self.nextID() config.addTargetParams( snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) cache['parm'][paramsKey] = paramsName, 1 if transportTarget.transportDomain in cache['tran']: transport, useCount = cache['tran'][transportTarget.transportDomain] transportTarget.verifyDispatcherCompatibility(snmpEngine) cache['tran'][transportTarget.transportDomain] = transport, useCount + 1 elif config.getTransport(snmpEngine, transportTarget.transportDomain): transportTarget.verifyDispatcherCompatibility(snmpEngine) else: transport = transportTarget.openClientMode() config.addTransport( snmpEngine, transportTarget.transportDomain, transport ) cache['tran'][transportTarget.transportDomain] = transport, 1 transportKey = (paramsName, transportTarget.transportDomain, transportTarget.transportAddr, transportTarget.tagList) if transportKey in cache['addr']: addrName, useCount = cache['addr'][transportKey] cache['addr'][transportKey] = addrName, useCount + 1 else: addrName = 'a%s' % self.nextID() config.addTargetAddr( snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, transportTarget.tagList ) cache['addr'][transportKey] = addrName, 1 return addrName, paramsName
# Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'demo', config.usmHMACMD5AuthProtocol, 'password' ) # user: usr-sha-none, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM
from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-md5-none, auth: MD5, priv: NONE config.addV3User( snmpEngine, 'there_was_snmpv3username', config.usmHMACMD5AuthProtocol, 'MazafakaRO' ) config.addTargetParams(snmpEngine, 'my-creds', 'there_was_snmpv3username', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router',
# # SNMPv1/2c setup (if you need to handle SNMPv1/v2c messages) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # SNMPv3/USM setup (if you need to handle SNMPv3 messages) # # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-none-none, auth: NONE, priv NONE config.addV3User( snmpEngine, 'usr-none-none' ) # user: usr-md5-none, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES
else: log.msg('ERROR: variation module "%s" not found' % variationModuleName) sys.exit(-1) # SNMP configuration snmpEngine = engine.SnmpEngine() if snmpVersion == 3: if v3PrivKey is None and v3AuthKey is None: secLevel = 'noAuthNoPriv' elif v3PrivKey is None: secLevel = 'authNoPriv' else: secLevel = 'authPriv' config.addV3User(snmpEngine, v3User, authProtocols[v3AuthProto], v3AuthKey, privProtocols[v3PrivProto], v3PrivKey) log.msg( 'SNMP version 3, Context EngineID: %s Context name: %s, SecurityName: %s, SecurityLevel: %s, Authentication key/protocol: %s/%s, Encryption (privacy) key/protocol: %s/%s' % (v3ContextEngineId and v3ContextEngineId.prettyPrint() or '<default>', v3Context and v3Context.prettyPrint() or '<default>', v3User, secLevel, v3AuthKey is None and '<NONE>' or v3AuthKey, v3AuthProto, v3PrivKey is None and '<NONE>' or v3PrivKey, v3PrivProto)) else: v3User = '******' secLevel = 'noAuthNoPriv' config.addV1System(snmpEngine, v3User, snmpCommunity) log.msg('SNMP version %s, Community name: %s' % (snmpVersion == 0 and '1' or '2c', snmpCommunity)) config.addTargetParams(snmpEngine, 'pms', v3User, secLevel, snmpVersion)
"""# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-aes, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() )
# UDP over IPv4, first listening interface/port config.addTransport(snmpEngine, udp.domainName + (1, ), udp.UdpTransport().openServerMode(('192.168.1.104', 162))) # UDP over IPv4, second listening interface/port # config.addTransport( # snmpEngine, # udp.domainName + (2,), # udp.UdpTransport().openServerMode(('127.0.0.1', 2162)) # ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV3User(snmpEngine, 'SNMP_ALIREZA', config.usmHMACMD5AuthProtocol, '12345678', config.usmDESPrivProtocol, '12345678', v2c.OctetString(hexValue='8000000001020304')) # config.addV1System(snmpEngine, 'alireza', 'alireza') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine
# Transport setup # UDP over IPv4 config.addTransport( snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # 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 snmpEngine = engine.SnmpEngine() config.addSocketTransport( snmpEngine, 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( snmpEngine, user, hashval, hash_key, cryval, cry_key, contextEngineId=v2c.OctetString(hexValue=engineid) ) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise
from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Initial OID prefix initialOID = rfc1902.ObjectName('1.3.6.1.2.1.1') # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-none-none, auth: none, priv: none config.addV3User( snmpEngine, 'usr-none-none', ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-none-none', 'noAuthNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr(
from pysnmp.proto.api import v2c # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # 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 config.addV3User(snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1') config.addV3User(snmpEngine, 'demo', config.usmHMACMD5AuthProtocol, 'demodemodemo', config.usmDESPrivProtocol, 'demodemodemo') # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used 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
# Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.DOMAIN_NAME, udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.USM_AUTH_HMAC96_MD5, 'authkey1', config.USM_PRIV_CBC56_DES, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'usr-sha-none', config.USM_AUTH_HMAC96_SHA, 'authkey1' ) # user: usr-sha-none, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.USM_AUTH_HMAC96_SHA, 'authkey1', config.USM_PRIV_CFB128_AES, 'privkey1' ) # Allow full MIB access for each user at VACM
def __init__(self, host, port, mibpaths): self.oid_mapping = {} self.databus_mediator = DatabusMediator(self.oid_mapping) # mapping between OID and databus keys # Create SNMP engine self.snmpEngine = engine.SnmpEngine() # path to custom mibs mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder mibSources = mibBuilder.getMibSources() for mibpath in mibpaths: mibSources += (builder.DirMibSource(mibpath), ) mibBuilder.setMibSources(*mibSources) # Transport setup udp_sock = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM) udp_sock.setsockopt(gevent.socket.SOL_SOCKET, gevent.socket.SO_BROADCAST, 1) udp_sock.bind((host, port)) self.server_port = udp_sock.getsockname()[1] # UDP over IPv4 self.addSocketTransport(self.snmpEngine, udp.domainName, udp_sock) # SNMPv1 config.addV1System(self.snmpEngine, 'public-read', 'public') # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User(self.snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1') # user: usr-sha-none, auth: SHA, priv NONE config.addV3User(self.snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1') # user: usr-sha-aes128, auth: SHA, priv AES/128 config.addV3User(self.snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1') # Allow full MIB access for each user at VACM config.addVacmUser(self.snmpEngine, 1, 'public-read', 'noAuthNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-md5-des', 'authPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-none', 'authNoPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) config.addVacmUser(self.snmpEngine, 3, 'usr-sha-aes128', 'authPriv', readSubTree=(1, 3, 6, 1, 2, 1), writeSubTree=(1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(self.snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context self.resp_app_get = conpot_cmdrsp.c_GetCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator) self.resp_app_set = conpot_cmdrsp.c_SetCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator) self.resp_app_next = conpot_cmdrsp.c_NextCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator) self.resp_app_bulk = conpot_cmdrsp.c_BulkCommandResponder( self.snmpEngine, snmpContext, self.databus_mediator)