Exemple #1
0
 def cfgNtfOrg(self, authData, transportTarget, notifyType, tagList):
     addrName, paramsName = self.cfgCmdGen(
         authData, transportTarget, tagList
         )
     k = paramsName, tagList, notifyType
     if self.__knownNotifyNames.has_key(k):
         notifyName, _ = self.__knownNotifyNames[k]
     else:
         notifyName = 'n%s' % cmdgen.nextID()
         config.addNotificationTarget(
             self.snmpEngine,
             notifyName,
             paramsName,
             tagList,
             notifyType
             )
         self.__knownNotifyNames[k] = notifyName, paramsName
     if not self.__knownAuths.has_key(authData):
         subTree = (1,3,6)
         config.addTrapUser(
             self.snmpEngine,
             authData.securityModel,
             authData.securityName,
             authData.securityLevel,
             subTree
             )
         self.__knownAuths[authData] = subTree
     if self.snmpContext is None:
         self.snmpContext = context.SnmpContext(self.snmpEngine)
         config.addContext(
             self.snmpEngine, ''  # this is leaky
         )
     return notifyName
    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)
Exemple #3
0
 def cfgNtfOrg(self, authData, transportTarget, notifyType):
     addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
     tagList = transportTarget.tagList.split()
     if not tagList:
         tagList = ['']
     for tag in tagList:
         k = paramsName, tag, notifyType
         if k in self.__knownNotifyNames:
             notifyName, _ = self.__knownNotifyNames[k]
         else:
             notifyName = 'n%s' % nextID()
             config.addNotificationTarget(self.snmpEngine, notifyName,
                                          paramsName, tag, notifyType)
             self.__knownNotifyNames[k] = notifyName, paramsName
     k = (authData.securityModel, authData.securityName,
          authData.securityLevel)
     if k not in self.__knownAuths:
         subTree = (1, 3, 6)
         config.addTrapUser(self.snmpEngine, authData.securityModel,
                            authData.securityName, authData.securityLevel,
                            subTree)
         self.__knownAuths[k] = subTree
     if self.snmpContext is None:
         self.snmpContext = context.SnmpContext(self.snmpEngine)
         config.addContext(
             self.snmpEngine,
             ''  # this is leaky
         )
     return notifyName
Exemple #4
0
    def __init__(self, snmpEngine=None, snmpContext=None):
        cmdgen.AsynCommandGenerator.__init__(self, snmpEngine)
        self.__asyncNtfOrg = AsyncNotificationOriginator()

        # grab/create MibViewController from/for the real AsyncCommandGen
        cache = self.__asyncNtfOrg._getCmdCache(self.snmpEngine)
        self.mibViewController = cache['mibViewController']

        if snmpContext is None:
            self.snmpContext = context.SnmpContext(self.snmpEngine)
            config.addContext(
                self.snmpEngine, ''  # this is leaky
            )
        else:
            self.snmpContext = snmpContext
Exemple #5
0
    def __init__(self, snmpEngine=None, snmpContext=None):
        if snmpEngine is None:
            self.snmpEngine = snmpEngine = SnmpEngine()
        else:
            self.snmpEngine = snmpEngine

        if snmpContext is None:
            self.snmpContext = context.SnmpContext(self.snmpEngine)
            config.addContext(
                self.snmpEngine, ''  # this is leaky
            )
        else:
            self.snmpContext = snmpContext

        self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine)
Exemple #6
0
    def __init__(self, snmpEngine=None, snmpContext=None):
        if snmpEngine is None:
            self.snmpEngine = snmpEngine = SnmpEngine()
        else:
            self.snmpEngine = snmpEngine

        if snmpContext is None:
            self.snmpContext = context.SnmpContext(self.snmpEngine)
            config.addContext(
                self.snmpEngine, ''  # this is leaky
            )
        else:
            self.snmpContext = snmpContext

        self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine)
Exemple #7
0
    def __init__(self, snmpEngine=None, snmpContext=None):
        cmdgen.AsynCommandGenerator.__init__(self, snmpEngine)
        self.__asyncNtfOrg = AsyncNotificationOriginator()

        # grab/create MibViewController from/for the real AsyncCommandGen
        cache = self.__asyncNtfOrg._getCmdCache(self.snmpEngine)
        self.mibViewController = cache['mibViewController']

        if snmpContext is None:
            self.snmpContext = context.SnmpContext(self.snmpEngine)
            config.addContext(
                self.snmpEngine,
                ''  # this is leaky
            )
        else:
            self.snmpContext = snmpContext
Exemple #8
0
 def run(self):
     """Run collector and start processing incoming traps"""
     config.addSocketTransport(
         self.snmp_engine,
         udp.domainName + (1, ),
         udp.UdpTransport().openServerMode(("0.0.0.0", 162)),
     )
     config.addV1System(self.snmp_engine, "new", "public")
     config.addContext(self.snmp_engine, "")
     ntfrcv.NotificationReceiver(self.snmp_engine, self.process_trap)
     self.snmp_engine.transportDispatcher.jobStarted(1)
     try:
         self.snmp_engine.transportDispatcher.runDispatcher()
     except Exception:
         self.snmp_engine.transportDispatcher.closeDispatcher()
         raise
Exemple #9
0
def initTarget(host='127.0.0.1', port=162, community='LIC_OSS'):
    #global snmpEngine, snmpContext, ntfOrg
    # Create SNMP engine instance
    snmpEngine = engine.SnmpEngine()
    
    # SecurityName <-> CommunityName mapping
    config.addV1System(snmpEngine, 'my-area', community)
    
    # Specify security settings per SecurityName (SNMPv2c -> 1)
    config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)
    
    # Setup transport endpoint and bind it with security settings yielding
    # a target name
    config.addSocketTransport(
        snmpEngine,
        udp.domainName,
        udp.UdpSocketTransport().openClientMode()
    )
    config.addTargetAddr(
        snmpEngine, 'my-nms',
        udp.domainName, (host, port),
        'my-creds',
        tagList='all-my-managers'
    )
    
    # Specify what kind of notification should be sent (TRAP or INFORM),
    # to what targets (chosen by tag) and what filter should apply to
    # the set of targets (selected by tag)
    config.addNotificationTarget(
        snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
    )
    
    # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
    # and SecurityName
    config.addContext(snmpEngine, '')
    config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1,3,6))
    
    # *** SNMP engine configuration is complete by this line ***
    
    # Create default SNMP context where contextEngineId == SnmpEngineId
    snmpContext = context.SnmpContext(snmpEngine)
    
    # Create Notification Originator App instance. 
    ntfOrg = ntforg.NotificationOriginator(snmpContext)
    return snmpEngine, ntfOrg
 def cfgNtfOrg(self, authData, transportTarget, notifyType):
     addrName, paramsName = self.cfgCmdGen(authData, transportTarget)
     tagList = transportTarget.tagList.split()
     if not tagList:
         tagList = ['']
     for tag in tagList:
         notifyNameKey = paramsName, tag, notifyType
         if notifyNameKey in self.__knownNotifyNames:
             notifyName, paramsName, useCount = self.__knownNotifyNames[notifyNameKey]
             self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, useCount + 1
         else:
             notifyName = 'n%s' % nextID()
             config.addNotificationTarget(
                 self.snmpEngine,
                 notifyName,
                 paramsName,
                 tag,
                 notifyType
             )
             self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, 1
     authDataKey = authData.securityName, authData.securityModel
     if  authDataKey in self.__knownAuths:
         authDataX, subTree, useCount = self.__knownAuths[authDataKey]
         self.__knownAuths[authDataKey] = authDataX, subTree, useCount + 1
     else:
         subTree = (1,3,6)
         config.addTrapUser(
             self.snmpEngine,
             authData.securityModel,
             authData.securityName,
             authData.securityLevel,
             subTree
         )
         self.__knownAuths[authDataKey] = authData, subTree, 1
     if self.snmpContext is None:
         self.snmpContext = context.SnmpContext(self.snmpEngine)
         config.addContext(
             self.snmpEngine, ''  # this is leaky
         )
     return notifyName
Exemple #11
0
def setTrapTypeForTag(snmpEngine, tag, kind='trap'):
    """Configure SNMP notification type per tag.

    Args:
        snmpEngine (object): pysnmp `SnmpEngine` class instance
        tag (str): SNMP tag to add to the list of tags used for issuing SNMP
            notifications.
        kind (str): SNMP notification type to use. Known values are
            'trap' and 'inform'.

    Returns:
        str: Group name to refer to all tagged configuration entries at
            once for selecting suitable ones for sending SNMP notifications.
    """
    targets = 'all-targets'

    config.addNotificationTarget(
        snmpEngine, targets, 'filter', tag, kind)

    config.addContext(snmpEngine, '')

    return targets
    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)
Exemple #13
0
def main():

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument(
        '-v', '--version', action='version',
        version=utils.TITLE)

    parser.add_argument(
        '-h', action='store_true', dest='usage',
        help='Brief usage message')

    parser.add_argument(
        '--help', action='store_true',
        help='Detailed help message')

    parser.add_argument(
        '--quiet', action='store_true',
        help='Do not print out informational messages')

    parser.add_argument(
        '--debug', choices=pysnmp_debug.flagMap,
        action='append', type=str, default=[],
        help='Enable one or more categories of SNMP debugging.')

    parser.add_argument(
        '--debug-asn1', choices=pyasn1_debug.FLAG_MAP,
        action='append', type=str, default=[],
        help='Enable one or more categories of ASN.1 debugging.')

    parser.add_argument(
        '--logging-method', type=lambda x: x.split(':'),
        metavar='=<%s[:args]>]' % '|'.join(log.METHODS_MAP),
        default='stderr', help='Logging method.')

    parser.add_argument(
        '--log-level', choices=log.LEVELS_MAP,
        type=str, default='info', help='Logging level.')

    parser.add_argument(
        '--reporting-method', type=lambda x: x.split(':'),
        metavar='=<%s[:args]>]' % '|'.join(ReportingManager.REPORTERS),
        default='null', help='Activity metrics reporting method.')

    parser.add_argument(
        '--daemonize', action='store_true',
        help='Disengage from controlling terminal and become a daemon')

    parser.add_argument(
        '--process-user', type=str,
        help='If run as root, switch simulator daemon to this user right '
             'upon binding privileged ports')

    parser.add_argument(
        '--process-group', type=str,
        help='If run as root, switch simulator daemon to this group right '
             'upon binding privileged ports')

    parser.add_argument(
        '--pid-file', metavar='<FILE>', type=str,
        default='/var/run/%s/%s.pid' % (__name__, os.getpid()),
        help='SNMP simulation data file to write records to')

    parser.add_argument(
        '--cache-dir', metavar='<DIR>', type=str,
        help='Location for SNMP simulation data file indices to create')

    parser.add_argument(
        '--force-index-rebuild', action='store_true',
        help='Rebuild simulation data files indices even if they seem '
             'up to date')

    parser.add_argument(
        '--validate-data', action='store_true',
        help='Validate simulation data files on daemon start-up')

    parser.add_argument(
        '--variation-modules-dir', metavar='<DIR>', type=str,
        action='append', default=[],
        help='Variation modules search path(s)')

    parser.add_argument(
        '--variation-module-options', metavar='<module[=alias][:args]>',
        type=str, action='append', default=[],
        help='Options for a specific variation module')

    parser.add_argument(
        '--v3-only', action='store_true',
        help='Trip legacy SNMP v1/v2c support to gain a little lesser memory '
             'footprint')

    parser.add_argument(
        '--transport-id-offset', type=int, default=0,
        help='Start numbering the last sub-OID of transport endpoint OIDs '
             'starting from this ID')

    parser.add_argument(
        '--max-var-binds', type=int, default=64,
        help='Maximum number of variable bindings to include in a single '
             'response')

    parser.add_argument(
        '--args-from-file', metavar='<FILE>', type=str,
        help='Read SNMP engine(s) command-line configuration from this '
             'file. Can be useful when command-line is too long')

    # We do not parse SNMP params with argparse, but we want its -h/--help
    snmp_helper = argparse.ArgumentParser(
        description=DESCRIPTION, add_help=False, parents=[parser])

    v3_usage = """\
Configure one or more independent SNMP engines. Each SNMP engine has a
distinct engine ID, its own set of SNMP USM users, one or more network
transport endpoints to listen on and its own simulation data directory.

Each SNMP engine configuration starts with `--v3-engine-id <arg>` parameter
followed by other configuration options up to the next `--v3-engine-id`
option or end of command line

Example
-------

$ snmp-command-responder \\
    --v3-engine-id auto \\
        --data-dir ./data --agent-udpv4-endpoint=127.0.0.1:1024 \\
    --v3-engine-id auto \\
        --data-dir ./data --agent-udpv4-endpoint=127.0.0.1:1025 \\ 
        --data-dir ./data --agent-udpv4-endpoint=127.0.0.1:1026

Besides network endpoints, simulated agents can be addressed by SNMPv1/v2c
community name or SNMPv3 context engine ID/name. These parameters are
configured automatically based on simulation data file paths relative to
`--data-dir`.
"""
    v3_group = snmp_helper.add_argument_group(v3_usage)

    v3_group.add_argument(
        '--v3-engine-id', type=str, metavar='<HEX|auto>', default='auto',
        help='SNMPv3 engine ID')

    v3_group.add_argument(
        '--v3-user', metavar='<STRING>',
        type=functools.partial(_parse_sized_string, min_length=1),
        help='SNMPv3 USM user (security) name')

    v3_group.add_argument(
        '--v3-auth-key', type=_parse_sized_string,
        help='SNMPv3 USM authentication key (must be > 8 chars)')

    v3_group.add_argument(
        '--v3-auth-proto', choices=AUTH_PROTOCOLS,
        type=lambda x: x.upper(), default='NONE',
        help='SNMPv3 USM authentication protocol')

    v3_group.add_argument(
        '--v3-priv-key', type=_parse_sized_string,
        help='SNMPv3 USM privacy (encryption) key (must be > 8 chars)')

    v3_group.add_argument(
        '--v3-priv-proto', choices=PRIV_PROTOCOLS,
        type=lambda x: x.upper(), default='NONE',
        help='SNMPv3 USM privacy (encryption) protocol')

    v3_group.add_argument(
        '--v3-context-engine-id',
        type=lambda x: univ.OctetString(hexValue=x[2:]),
        help='SNMPv3 context engine ID')

    v3_group.add_argument(
        '--v3-context-name', type=str, default='',
        help='SNMPv3 context engine ID')

    v3_group.add_argument(
        '--agent-udpv4-endpoint', type=endpoints.parse_endpoint,
        metavar='<[X.X.X.X]:NNNNN>',
        help='SNMP agent UDP/IPv4 address to listen on (name:port)')

    v3_group.add_argument(
        '--agent-udpv6-endpoint',
        type=functools.partial(endpoints.parse_endpoint, ipv6=True),
        metavar='<[X:X:..X]:NNNNN>',
        help='SNMP agent UDP/IPv6 address to listen on ([name]:port)')

    v3_group.add_argument(
        '--data-dir',
        type=str, metavar='<DIR>',
        help='SNMP simulation data recordings directory.')

    args, unparsed_args = parser.parse_known_args()

    if args.usage:
        snmp_helper.print_usage(sys.stderr)
        return 1

    if args.help:
        snmp_helper.print_help(sys.stderr)
        return 1

    _, unknown_args = snmp_helper.parse_known_args(unparsed_args)
    if unknown_args:
        sys.stderr.write(
            'ERROR: Unknown command-line parameter(s) '
            '%s\r\n' % ' '.join(unknown_args))
        snmp_helper.print_usage(sys.stderr)
        return 1

    # Reformat unparsed args into a list of (option, value) tuples
    snmp_args = []
    name = None

    for opt in unparsed_args:
        if '=' in opt:
            snmp_args.append(opt.split('='))

        elif name:
            snmp_args.append((name, opt))
            name = None

        else:
            name = opt

    if name:
        sys.stderr.write(
            'ERROR: Non-paired command-line key-value parameter '
            '%s\r\n' % name)
        snmp_helper.print_usage(sys.stderr)
        return 1

    if args.cache_dir:
        confdir.cache = args.cache_dir

    if args.variation_modules_dir:
        confdir.variation = args.variation_modules_dir

    variation_modules_options = variation.parse_modules_options(
        args.variation_module_options)

    if args.args_from_file:
        try:
            with open(args.args_from_file) as fl:
                snmp_args.extend([handler.split('=', 1) for handler in fl.read().split()])

        except Exception as exc:
            sys.stderr.write(
                'ERROR: file %s opening failure: '
                '%s\r\n' % (args.args_from_file, exc))
            snmp_helper.print_usage(sys.stderr)
            return 1

    with daemon.PrivilegesOf(args.process_user, args.process_group):

        proc_name = os.path.basename(sys.argv[0])

        try:
            log.set_logger(proc_name, *args.logging_method, force=True)

            if args.log_level:
                log.set_level(args.log_level)

        except SnmpsimError as exc:
            sys.stderr.write('%s\r\n' % exc)
            snmp_helper.print_usage(sys.stderr)
            return 1

        try:
            ReportingManager.configure(*args.reporting_method)

        except SnmpsimError as exc:
            sys.stderr.write('%s\r\n' % exc)
            snmp_helper.print_usage(sys.stderr)
            return 1

    if args.daemonize:
        try:
            daemon.daemonize(args.pid_file)

        except Exception as exc:
            sys.stderr.write(
                'ERROR: cant daemonize process: %s\r\n' % exc)
            snmp_helper.print_usage(sys.stderr)
            return 1

    if not os.path.exists(confdir.cache):
        try:
            with daemon.PrivilegesOf(args.process_user, args.process_group):
                os.makedirs(confdir.cache)

        except OSError as exc:
            log.error('failed to create cache directory "%s": '
                      '%s' % (confdir.cache, exc))
            return 1

        else:
            log.info('Cache directory "%s" created' % confdir.cache)

    variation_modules = variation.load_variation_modules(
        confdir.variation, variation_modules_options)

    with daemon.PrivilegesOf(args.process_user, args.process_group):
        variation.initialize_variation_modules(
            variation_modules, mode='variating')

    def configure_managed_objects(
            data_dirs, data_index_instrum_controller, snmp_engine=None,
            snmp_context=None):
        """Build pysnmp Managed Objects base from data files information"""

        _mib_instrums = {}
        _data_files = {}

        for dataDir in data_dirs:

            log.info(
                'Scanning "%s" directory for %s data '
                'files...' % (dataDir, ','.join(
                    [' *%s%s' % (os.path.extsep, x.ext)
                     for x in variation.RECORD_TYPES.values()])))

            if not os.path.exists(dataDir):
                log.info('Directory "%s" does not exist' % dataDir)
                continue

            log.msg.inc_ident()

            for (full_path,
                 text_parser,
                 community_name) in datafile.get_data_files(dataDir):
                if community_name in _data_files:
                    log.error(
                        'ignoring duplicate Community/ContextName "%s" for data '
                        'file %s (%s already loaded)' % (community_name, full_path,
                                                         _data_files[community_name]))
                    continue

                elif full_path in _mib_instrums:
                    mib_instrum = _mib_instrums[full_path]
                    log.info('Configuring *shared* %s' % (mib_instrum,))

                else:
                    data_file = datafile.DataFile(
                        full_path, text_parser, variation_modules)
                    data_file.index_text(args.force_index_rebuild, args.validate_data)

                    MibController = controller.MIB_CONTROLLERS[data_file.layout]
                    mib_instrum = MibController(data_file)

                    _mib_instrums[full_path] = mib_instrum
                    _data_files[community_name] = full_path

                    log.info('Configuring %s' % (mib_instrum,))

                log.info('SNMPv1/2c community name: %s' % (community_name,))

                agent_name = md5(
                    univ.OctetString(community_name).asOctets()).hexdigest()

                context_name = agent_name

                if not args.v3_only:
                    # snmpCommunityTable::snmpCommunityIndex can't be > 32
                    config.addV1System(
                        snmp_engine, agent_name, community_name,
                        contextName=context_name)

                snmp_context.registerContextName(context_name, mib_instrum)

                if len(community_name) <= 32:
                    snmp_context.registerContextName(community_name, mib_instrum)

                data_index_instrum_controller.add_data_file(
                    full_path, community_name, context_name)

                log.info(
                    'SNMPv3 Context Name: %s'
                    '%s' % (context_name, len(community_name) <= 32 and
                            ' or %s' % community_name or ''))

            log.msg.dec_ident()

        del _mib_instrums
        del _data_files

    # Bind transport endpoints
    for idx, opt in enumerate(snmp_args):
        if opt[0] == '--agent-udpv4-endpoint':
            snmp_args[idx] = (
                opt[0], endpoints.IPv4TransportEndpoints().add(opt[1]))

        elif opt[0] == '--agent-udpv6-endpoint':
            snmp_args[idx] = (
                opt[0], endpoints.IPv6TransportEndpoints().add(opt[1]))

    # Start configuring SNMP engine(s)

    transport_dispatcher = AsyncoreDispatcher()

    transport_dispatcher.registerRoutingCbFun(lambda td, t, d: td)

    if not snmp_args or snmp_args[0][0] != '--v3-engine-id':
        snmp_args.insert(0, ('--v3-engine-id', 'auto'))

    if snmp_args and snmp_args[-1][0] != 'end-of-options':
        snmp_args.append(('end-of-options', ''))

    snmp_engine = None

    transport_index = {
        'udpv4': args.transport_id_offset,
        'udpv6': args.transport_id_offset,
    }

    for opt in snmp_args:

        if opt[0] in ('--v3-engine-id', 'end-of-options'):

            if snmp_engine:

                log.info('--- SNMP Engine configuration')

                log.info(
                    'SNMPv3 EngineID: '
                    '%s' % (hasattr(snmp_engine, 'snmpEngineID')
                            and snmp_engine.snmpEngineID.prettyPrint() or '<unknown>',))

                if not v3_context_engine_ids:
                    v3_context_engine_ids.append((None, []))

                log.msg.inc_ident()

                log.info('--- Simulation data recordings configuration')

                for v3_context_engine_id, ctx_data_dirs in v3_context_engine_ids:
                    snmp_context = context.SnmpContext(snmp_engine, v3_context_engine_id)
                    # unregister default context
                    snmp_context.unregisterContextName(null)

                    log.info(
                        'SNMPv3 Context Engine ID: '
                        '%s' % snmp_context.contextEngineId.prettyPrint())

                    data_index_instrum_controller = controller.DataIndexInstrumController()

                    with daemon.PrivilegesOf(args.process_user, args.process_group):
                        configure_managed_objects(
                            ctx_data_dirs or data_dirs or confdir.data,
                            data_index_instrum_controller,
                            snmp_engine,
                            snmp_context
                        )

                # Configure access to data index

                config.addV1System(snmp_engine, 'index',
                                   'index', contextName='index')

                log.info('--- SNMPv3 USM configuration')

                if not v3_users:
                    v3_users = ['simulator']
                    v3_auth_keys[v3_users[0]] = 'auctoritas'
                    v3_auth_protos[v3_users[0]] = 'MD5'
                    v3_priv_keys[v3_users[0]] = 'privatus'
                    v3_priv_protos[v3_users[0]] = 'DES'

                for v3User in v3_users:
                    if v3User in v3_auth_keys:
                        if v3User not in v3_auth_protos:
                            v3_auth_protos[v3User] = 'MD5'

                    elif v3User in v3_auth_protos:
                        log.error(
                            'auth protocol configured without key for user '
                            '%s' % v3User)
                        return 1

                    else:
                        v3_auth_keys[v3User] = None
                        v3_auth_protos[v3User] = 'NONE'

                    if v3User in v3_priv_keys:
                        if v3User not in v3_priv_protos:
                            v3_priv_protos[v3User] = 'DES'

                    elif v3User in v3_priv_protos:
                        log.error(
                            'privacy protocol configured without key for user '
                            '%s' % v3User)
                        return 1

                    else:
                        v3_priv_keys[v3User] = None
                        v3_priv_protos[v3User] = 'NONE'

                    if (AUTH_PROTOCOLS[v3_auth_protos[v3User]] == config.usmNoAuthProtocol and
                            PRIV_PROTOCOLS[v3_priv_protos[v3User]] != config.usmNoPrivProtocol):
                        log.error(
                            'privacy impossible without authentication for USM user '
                            '%s' % v3User)
                        return 1

                    try:
                        config.addV3User(
                            snmp_engine,
                            v3User,
                            AUTH_PROTOCOLS[v3_auth_protos[v3User]],
                            v3_auth_keys[v3User],
                            PRIV_PROTOCOLS[v3_priv_protos[v3User]],
                            v3_priv_keys[v3User])

                    except error.PySnmpError as exc:
                        log.error(
                            'bad USM values for user %s: '
                            '%s' % (v3User, exc))
                        return 1

                    log.info('SNMPv3 USM SecurityName: %s' % v3User)

                    if AUTH_PROTOCOLS[v3_auth_protos[v3User]] != config.usmNoAuthProtocol:
                        log.info(
                            'SNMPv3 USM authentication key: %s, '
                            'authentication protocol: '
                            '%s' % (v3_auth_keys[v3User], v3_auth_protos[v3User]))

                    if PRIV_PROTOCOLS[v3_priv_protos[v3User]] != config.usmNoPrivProtocol:
                        log.info(
                            'SNMPv3 USM encryption (privacy) key: %s, '
                            'encryption protocol: '
                            '%s' % (v3_priv_keys[v3User], v3_priv_protos[v3User]))

                snmp_context.registerContextName('index', data_index_instrum_controller)

                log.info(
                    'Maximum number of variable bindings in SNMP response: '
                    '%s' % local_max_var_binds)

                log.info('--- Transport configuration')

                if not agent_udpv4_endpoints and not agent_udpv6_endpoints:
                    log.error(
                        'agent endpoint address(es) not specified for SNMP '
                        'engine ID %s' % v3_engine_id)
                    return 1

                for agent_udpv4_endpoint in agent_udpv4_endpoints:
                    transport_domain = udp.domainName + (transport_index['udpv4'],)
                    transport_index['udpv4'] += 1

                    snmp_engine.registerTransportDispatcher(
                        transport_dispatcher, transport_domain)

                    config.addSocketTransport(
                        snmp_engine, transport_domain, agent_udpv4_endpoint[0])

                    log.info(
                        'Listening at UDP/IPv4 endpoint %s, transport ID '
                        '%s' % (agent_udpv4_endpoint[1],
                                '.'.join([str(handler) for handler in transport_domain])))

                for agent_udpv6_endpoint in agent_udpv6_endpoints:
                    transport_domain = udp6.domainName + (transport_index['udpv6'],)
                    transport_index['udpv6'] += 1

                    snmp_engine.registerTransportDispatcher(
                        transport_dispatcher, transport_domain)

                    config.addSocketTransport(
                        snmp_engine,
                        transport_domain, agent_udpv6_endpoint[0])

                    log.info(
                        'Listening at UDP/IPv6 endpoint %s, transport ID '
                        '%s' % (agent_udpv6_endpoint[1],
                                '.'.join([str(handler) for handler in transport_domain])))

                # SNMP applications
                GetCommandResponder(snmp_engine, snmp_context)
                SetCommandResponder(snmp_engine, snmp_context)
                NextCommandResponder(snmp_engine, snmp_context)
                BulkCommandResponder(
                    snmp_engine, snmp_context).maxVarBinds = local_max_var_binds

                log.msg.dec_ident()

                if opt[0] == 'end-of-options':
                    # Load up the rest of MIBs while running privileged
                    (snmp_engine
                     .msgAndPduDsp
                     .mibInstrumController
                     .mibBuilder.loadModules())
                    break

            # Prepare for next engine ID configuration

            v3_context_engine_ids = []
            data_dirs = []
            local_max_var_binds = args.max_var_binds
            v3_users = []
            v3_auth_keys = {}
            v3_auth_protos = {}
            v3_priv_keys = {}
            v3_priv_protos = {}
            agent_udpv4_endpoints = []
            agent_udpv6_endpoints = []

            try:
                v3_engine_id = opt[1]
                if not v3_engine_id or v3_engine_id.lower() == 'auto':
                    snmp_engine = engine.SnmpEngine()

                else:
                    snmp_engine = engine.SnmpEngine(
                        snmpEngineID=univ.OctetString(hexValue=v3_engine_id))

            except Exception as exc:
                log.error(
                    'SNMPv3 Engine initialization failed, EngineID "%s": '
                    '%s' % (v3_engine_id, exc))
                return 1

            config.addContext(snmp_engine, '')

        elif opt[0] == '--v3-context-engine-id':
            v3_context_engine_ids.append((univ.OctetString(hexValue=opt[1]), []))

        elif opt[0] == '--data-dir':
            if v3_context_engine_ids:
                v3_context_engine_ids[-1][1].append(opt[1])

            else:
                data_dirs.append(opt[1])

        elif opt[0] == '--max-varbinds':
            local_max_var_binds = opt[1]

        elif opt[0] == '--v3-user':
            v3_users.append(opt[1])

        elif opt[0] == '--v3-auth-key':
            if not v3_users:
                log.error('--v3-user should precede %s' % opt[0])
                return 1

            if v3_users[-1] in v3_auth_keys:
                log.error(
                    'repetitive %s option for user %s' % (opt[0], v3_users[-1]))
                return 1

            v3_auth_keys[v3_users[-1]] = opt[1]

        elif opt[0] == '--v3-auth-proto':
            if opt[1].upper() not in AUTH_PROTOCOLS:
                log.error('bad v3 auth protocol %s' % opt[1])
                return 1

            else:
                if not v3_users:
                    log.error('--v3-user should precede %s' % opt[0])
                    return 1

                if v3_users[-1] in v3_auth_protos:
                    log.error(
                        'repetitive %s option for user %s' % (opt[0], v3_users[-1]))
                    return 1

                v3_auth_protos[v3_users[-1]] = opt[1].upper()

        elif opt[0] == '--v3-priv-key':
            if not v3_users:
                log.error('--v3-user should precede %s' % opt[0])
                return 1

            if v3_users[-1] in v3_priv_keys:
                log.error(
                    'repetitive %s option for user %s' % (opt[0], v3_users[-1]))
                return 1

            v3_priv_keys[v3_users[-1]] = opt[1]

        elif opt[0] == '--v3-priv-proto':
            if opt[1].upper() not in PRIV_PROTOCOLS:
                log.error('bad v3 privacy protocol %s' % opt[1])
                return 1

            else:
                if not v3_users:
                    log.error('--v3-user should precede %s' % opt[0])
                    return 1

                if v3_users[-1] in v3_priv_protos:
                    log.error(
                        'repetitive %s option for user %s' % (opt[0], v3_users[-1]))
                    return 1

                v3_priv_protos[v3_users[-1]] = opt[1].upper()

        elif opt[0] == '--agent-udpv4-endpoint':
            agent_udpv4_endpoints.append(opt[1])

        elif opt[0] == '--agent-udpv6-endpoint':
            agent_udpv6_endpoints.append(opt[1])

    transport_dispatcher.jobStarted(1)  # server job would never finish

    with daemon.PrivilegesOf(args.process_user, args.process_group, final=True):

        try:
            transport_dispatcher.runDispatcher()

        except KeyboardInterrupt:
            log.info('Shutting down process...')

        finally:
            if variation_modules:
                log.info('Shutting down variation modules:')

                for name, contexts in variation_modules.items():
                    body = contexts[0]
                    try:
                        body['shutdown'](options=body['args'], mode='variation')

                    except Exception as exc:
                        log.error(
                            'Variation module "%s" shutdown FAILED: '
                            '%s' % (name, exc))

                    else:
                        log.info('Variation module "%s" shutdown OK' % name)

            transport_dispatcher.closeDispatcher()

            log.info('Process terminated')

    return 0
Exemple #14
0
	def start(self):
		if self._engine is None:
			# Create SNMP engine with autogenernated engineID and pre-bound
			# to socket transport dispatcher
			self._engine = engine.SnmpEngine()
			
			# Setup UDP over IPv4 transport endpoint
		try:
			iface = ('0.0.0.0', self.port)
			self._logger.info("[pid: %d] Starting SNMP server on %s:%d",  os.getpid(), iface[0], iface[1])
			config.addSocketTransport(
			self._engine,
			udp.domainName,
			udp.UdpSocketTransport().openServerMode(iface)
			)
		except CarrierError:
			self._logger.error('Can\'t run SNMP agent on port %d: Address already in use', self.port)
			raise
		
		mibBuilder = self._engine.msgAndPduDsp.mibInstrumController.mibBuilder
			
		MibSources = mibBuilder.getMibPath()
		sources =  ['/mibs','/mibs/instances']
		for source in sources:
			MibSources += ((os.path.realpath(os.path.dirname(__file__) + source), ))
		apply(mibBuilder.setMibPath, MibSources)
			
		try:
			mibBuilder.loadModules(*self._modules)
		except SmiError:
			self._logger.warn('Can\'t load modules')
			raise

		config.addV1System(self._engine, self._security_name, self._community_name)
			
		# VACM setup
		config.addContext(self._engine, '')
		config.addRwUser(self._engine, 1, self._security_name, 'noAuthNoPriv', (1,3,6)) # v1
		config.addRwUser(self._engine, 2, self._security_name, 'noAuthNoPriv', (1,3,6)) # v2c
			
		# SNMP context
		snmpContext = context.SnmpContext(self._engine)
		# Apps registration
		cmdrsp.GetCommandResponder(self._engine, snmpContext)
		cmdrsp.SetCommandResponder(self._engine, snmpContext)
		cmdrsp.NextCommandResponder(self._engine, snmpContext)
		cmdrsp.BulkCommandResponder(self._engine, snmpContext)
			
		# Start server
		self._logger.debug('Starting transport dispatcher')
		self._engine.transportDispatcher.jobStarted(1)
		try:
			self._logger.debug('Run transport dispatcher')
			self._engine.transportDispatcher.runDispatcher()
		except select.error, e:
			if e.args[0] == 9: 
				# 'Bad file descriptor'
				# Throws when dispatcher closed from another thread
				pass
			else:
				raise
# Second target
config.addTargetAddr(
    snmpEngine, "my-nms-2", udp.domainName, ("195.218.195.228", 162), "my-creds", tagList="all-my-managers"
)
# Third target
config.addTargetAddr(
    snmpEngine, "my-nms-3", udp.domainName, ("195.218.195.228", 162), "my-creds", tagList="all-my-managers"
)

# Specify what kind of notification should be sent (TRAP or INFORM)
# to what targets (chosen by tag) and with what credentials.
config.addNotificationTarget(snmpEngine, "my-notification", "my-creds", "all-my-managers", "trap")

# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
# and SecurityName
config.addContext(snmpEngine, "")
config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv", (), (), (1, 3, 6))

# *** SNMP engine configuration is complete by this line ***

# Create Notification Originator App instance.
ntfOrg = ntforg.NotificationOriginator()

# Build and submit notification message to dispatcher
ntfOrg.sendVarBinds(
    snmpEngine,
    # Notification targets
    "my-notification",  # notification targets
    None,
    "",  # contextEngineId, contextName
    # var-binds
Exemple #16
0
    def __init__(self,
                 mibPath,
                 temperatureValue,
                 snmpRelays,
                 criticalStatus=True):
        from types import ListType, TupleType, StringTypes
        from re import compile, search
        from socket import gethostbyname

        extractPaths = compile(r'[,:]')
        checkIP = compile(r'(\d{1,3}\.){3}\d{1,3}')

        # Create SNMP engine instance
        self.snmpEngine = engine.SnmpEngine()

        if not temperatureValue:
            raise ValueError, 'A temperature must be provided'

        self.temperature = temperatureValue
        #print "============>mibPath type: %s" %type(mibPath)
        if type(mibPath) in StringTypes:
            mibPathTuple = tuple(extractPaths.split(mibPath))
        elif type(mibPath) in (ListType, TupleType):
            mibPathTuple = tuple(mibPath)
        else:
            mibPathTuple = ('/usr/local/share/snmp/python/', )

        mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

        #print mibPathTuple
        mibSources = mibBuilder.getMibPath() + mibPathTuple
        mibBuilder.setMibPath(*mibSources)

        mibBuilder.loadModules('USC-IGFAE-MIB')

        if type(snmpRelays) in StringTypes:
            snmpRelays = snmpRelays.split(',')
        elif not type(snmpRelays) in (ListType, TupleType):
            raise TypeError, 'The list of SNMP relays must be a string or a list or tuple of strings'

        (temperatureCritical, temperatureOK,
         self.roomTemp) = mibBuilder.importSymbols('USC-IGFAE-MIB',
                                                   'temperatureCritical',
                                                   'temperatureOK', 'roomTemp')

        # SecurityName <-> CommunityName mapping
        config.addV1System(self.snmpEngine, 'Arduino', 'ups')

        # Specify security settings per SecurityName (SNMPv2c -> 1)
        config.addTargetParams(self.snmpEngine, 'creds', 'Arduino',
                               'noAuthNoPriv', 0)

        # Setup transport endpoint and bind it with security settings yielding
        # a target name
        config.addSocketTransport(self.snmpEngine, udp.domainName,
                                  udp.UdpSocketTransport().openClientMode())

        index = 0
        for machine in snmpRelays:
            index = index + 1
            if not checkIP.match(machine):
                try:
                    machine = gethostbyname(machine)
                except:
                    continue

            #print "==============>SNMP relay  IP: %s" % machine
            config.addTargetAddr(self.snmpEngine,
                                 'NMS%s' % index,
                                 udp.domainName, (machine, 162),
                                 'creds',
                                 tagList='managers')

        # Specify what kind of notification should be sent (TRAP or INFORM),
        # to what targets (chosen by tag) and what filter should apply to
        # the set of targets (selected by tag)
        config.addNotificationTarget(self.snmpEngine, 'sendShutdownTrap',
                                     'my-filter', 'managers', 'trap')

        # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
        # and SecurityName
        config.addContext(self.snmpEngine, '')
        config.addVacmUser(self.snmpEngine, 1, 'Arduino', 'noAuthNoPriv', (),
                           (), (1, 3, 6))

        # *** SNMP engine configuration is complete by this line ***

        # Create default SNMP context where contextEngineId == SnmpEngineId
        snmpContext = context.SnmpContext(self.snmpEngine)

        if criticalStatus:
            self.trap = temperatureCritical
        else:
            self.trap = temperatureOK

        # Create Notification Originator App instance.
        ntforg.NotificationOriginator.__init__(self, snmpContext)
Exemple #17
0
    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()
                   contextEngineId=snmpContext.contextEngineId,
                   contextName=contextName)

# VACM configuration settings

securityModel = 2  # SNMPv2c
securityLevel = 1  # noAuthNoPriv

vacmGroup = 'my-group'
readViewName = 'my-read-view'

# We will match by context name prefix
contextPrefix = contextName[:1]

# Populate SNMP-VIEW-BASED-ACM-MIB::vacmContextTable
config.addContext(snmpEngine, contextName)

# Populate SNMP-VIEW-BASED-ACM-MIB::vacmSecurityToGroupTable
config.addVacmGroup(snmpEngine, vacmGroup, securityModel, securityName)

# Populate SNMP-VIEW-BASED-ACM-MIB::vacmAccessTable
config.addVacmAccess(snmpEngine, vacmGroup, contextPrefix, securityModel,
                     securityLevel, 'prefix', readViewName, '', '')

# Populate SNMP-VIEW-BASED-ACM-MIB::vacmViewTreeFamilyTable

# Allow the whole system subtree
config.addVacmView(snmpEngine, readViewName, 'included', '1.3.6.1.2.1.1.1',
                   '1.1.1.1.1.1.1.0')

# ...but exclude one sub-branch (just one scalar OID)
Exemple #19
0
    snmpEngine, 'my-nms',
    udp.domainName, ('104.236.166.95', 162),
    'my-creds',
    tagList='all-my-managers'
)

# Specify what kind of notification should be sent (TRAP or INFORM),
# to what targets (chosen by tag) and what filter should apply to
# the set of targets (selected by tag)
config.addNotificationTarget(
    snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform'
)

# Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel
# and SecurityName
config.addContext(snmpEngine, '')
config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (1, 3, 6))

# *** SNMP engine configuration is complete by this line ***

# Create Notification Originator App instance. 
ntfOrg = ntforg.NotificationOriginator()


# Error/confirmation receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, sendRequestHandle, errorIndication,
          errorStatus, errorIndex, varBinds, cbCtx):
    print('Notification %s, status - %s' % (
        sendRequestHandle, errorIndication and errorIndication or 'delivered'
    )
Exemple #20
0
    def start(self):
        if self._engine is None:
            # Create SNMP engine with autogenernated engineID and pre-bound
            # to socket transport dispatcher
            self._engine = engine.SnmpEngine()

            # Setup UDP over IPv4 transport endpoint
        try:
            iface = ('0.0.0.0', self.port)
            self._logger.info("[pid: %d] Starting SNMP server on %s:%d",  os.getpid(), iface[0], iface[1])
            config.addSocketTransport(
            self._engine,
            udp.domainName,
            udp.UdpSocketTransport().openServerMode(iface)
            )
        except CarrierError:
            self._logger.error('Can\'t run SNMP agent on port %d: Address already in use', self.port)
            raise

        mibBuilder = self._engine.msgAndPduDsp.mibInstrumController.mibBuilder

        MibSources = mibBuilder.getMibPath()
        sources =  ['/mibs','/mibs/instances']
        for source in sources:
            MibSources += ((os.path.realpath(os.path.dirname(__file__) + source), ))
        apply(mibBuilder.setMibPath, MibSources)

        try:
            mibBuilder.loadModules(*self._modules)
        except SmiError:
            self._logger.warn('Can\'t load modules')
            raise

        config.addV1System(self._engine, self._security_name, self._community_name)

        # VACM setup
        config.addContext(self._engine, '')
        config.addRwUser(self._engine, 1, self._security_name, 'noAuthNoPriv', (1,3,6)) # v1
        config.addRwUser(self._engine, 2, self._security_name, 'noAuthNoPriv', (1,3,6)) # v2c

        # SNMP context
        snmpContext = context.SnmpContext(self._engine)
        # Apps registration
        cmdrsp.GetCommandResponder(self._engine, snmpContext)
        cmdrsp.SetCommandResponder(self._engine, snmpContext)
        cmdrsp.NextCommandResponder(self._engine, snmpContext)
        cmdrsp.BulkCommandResponder(self._engine, snmpContext)

        # Start server
        self._logger.debug('Starting transport dispatcher')
        self._engine.transportDispatcher.jobStarted(1)
        try:
            self._logger.debug('Run transport dispatcher')
            self._engine.transportDispatcher.runDispatcher()
        except select.error, e:
            if e.args[0] == 9:
                # 'Bad file descriptor'
                # Throws when dispatcher closed from another thread
                pass
            else:
                raise
Exemple #21
0
def sendTheTrap():
    uptime = getUptime()
    # Create SNMP engine instance with specific (and locally unique)
    # SnmpEngineId -- it must also be known to the receiving party
    # and configured at its VACM users table.
    snmpEngine = engine.SnmpEngine(snmpEngineID=v2c.OctetString(
        hexValue='0102030405060708'))

    # Add USM user
    config.addV3User(snmpEngine, userConfig['DEFAULT']['SNMPUSER'],
                     config.usmHMAC128SHA224AuthProtocol,
                     userConfig['DEFAULT']['SNMPAUTH'],
                     config.usmAesCfb192Protocol,
                     userConfig['DEFAULT']['SNMPPRIV'])

    config.addTargetParams(snmpEngine, userConfig['DEFAULT']['SNMPAUTH'],
                           userConfig['DEFAULT']['SNMPUSER'], 'authPriv')

    # 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,
                         (userConfig['DEFAULT']['SNMPMANAGERIP'],
                          int(userConfig['DEFAULT']['SNMPMANAGERPORT'])),
                         userConfig['DEFAULT']['SNMPAUTH'],
                         tagList='all-my-managers')

    # Specify what kind of notification should be sent (TRAP or INFORM),
    # to what targets (chosen by tag) and what filter should apply to
    # the set of targets (selected by tag)
    config.addNotificationTarget(snmpEngine, 'my-notification', 'my-filter',
                                 'all-my-managers', 'trap')

    # Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel
    # and SecurityName
    config.addContext(snmpEngine, '')
    config.addVacmUser(snmpEngine, 3, userConfig['DEFAULT']['SNMPUSER'],
                       'authPriv', (), (), (1, 3, 6), 'aContextName')

    # *** SNMP engine configuration is complete by this line ***

    # Create Notification Originator App instance.
    ntfOrg = ntforg.NotificationOriginator()

    # Build and submit notification message to dispatcher
    ntfOrg.sendVarBinds(
        snmpEngine,
        # Notification targets
        'my-notification',  # notification targets
        None,
        'aContextName',  # contextEngineId, contextName
        # var-binds
        [((1, 3, 6, 1, 2, 1, 1, 3, 0), v2c.OctetString(uptime)),
         ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0),
          v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))),
         ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(socket.getfqdn())),
         ((1, 3, 6, 1, 4, 1, 6876, 4, 50, 1, 2, 10, 0),
          v2c.OctetString('Application')),
         ((1, 3, 6, 1, 4, 1, 6876, 4, 50, 1, 2, 11, 0),
          v2c.OctetString('Performance')),
         ((1, 3, 6, 1, 4, 1, 6876, 4, 50, 1, 2, 12, 0),
          v2c.OctetString('critical')),
         ((1, 3, 6, 1, 4, 1, 6876, 4, 50, 1, 2, 19, 0),
          v2c.OctetString('health')),
         ((1, 3, 6, 1, 4, 1, 6876, 4, 50, 1, 2, 20, 0),
          v2c.OctetString('vROpsExternalMonitorService.py')),
         ((1, 3, 6, 1, 4, 1, 6876, 4, 50, 1, 2, 50, 0),
          v2c.OctetString(
              'vROps services are having issues, please check nodes'))])

    print('Notification is scheduled to be sent')

    # Run I/O dispatcher which would send pending message and process response
    snmpEngine.transportDispatcher.runDispatcher()
Exemple #22
0
  def __init__(self, mibPath, temperatureValue, snmpRelays, criticalStatus=True):
    from types import ListType, TupleType,StringTypes
    from re import compile,search
    from socket import gethostbyname

    extractPaths=compile(r'[,:]')
    checkIP=compile(r'(\d{1,3}\.){3}\d{1,3}')

    # Create SNMP engine instance
    self.snmpEngine = engine.SnmpEngine()

    if not temperatureValue:
      raise ValueError, 'A temperature must be provided'
    
    self.temperature=temperatureValue
    #print "============>mibPath type: %s" %type(mibPath)
    if type(mibPath) in StringTypes:
      mibPathTuple=tuple(extractPaths.split(mibPath))
    elif type(mibPath) in (ListType, TupleType):
      mibPathTuple=tuple(mibPath)
    else:
      mibPathTuple=('/usr/local/share/snmp/python/',)

    mibBuilder = self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    #print mibPathTuple
    mibSources = mibBuilder.getMibPath() + mibPathTuple
    mibBuilder.setMibPath(*mibSources)

    mibBuilder.loadModules( 'USC-IGFAE-MIB' )

    if type(snmpRelays) in StringTypes:
      snmpRelays=snmpRelays.split(',')
    elif not type(snmpRelays) in (ListType,TupleType):
      raise TypeError, 'The list of SNMP relays must be a string or a list or tuple of strings'
    
    
    (temperatureCritical, temperatureOK, self.roomTemp) = mibBuilder.importSymbols('USC-IGFAE-MIB','temperatureCritical', 'temperatureOK', 'roomTemp' )

    # SecurityName <-> CommunityName mapping
    config.addV1System(self.snmpEngine, 'Arduino', 'ups')

    # Specify security settings per SecurityName (SNMPv2c -> 1)
    config.addTargetParams(self.snmpEngine, 'creds', 'Arduino', 'noAuthNoPriv', 0)

    # Setup transport endpoint and bind it with security settings yielding
    # a target name
    config.addSocketTransport(
      self.snmpEngine,
      udp.domainName,
      udp.UdpSocketTransport().openClientMode()
    )

    index=0
    for machine in snmpRelays:
      index=index+1
      if not checkIP.match(machine):
        try:
          machine=gethostbyname(machine)
        except:
          continue

      #print "==============>SNMP relay  IP: %s" % machine
      config.addTargetAddr(
        self.snmpEngine, 'NMS%s' % index,
        udp.domainName, (machine, 162),
        'creds',
        tagList='managers'
      )

    # Specify what kind of notification should be sent (TRAP or INFORM),
    # to what targets (chosen by tag) and what filter should apply to
    # the set of targets (selected by tag)
    config.addNotificationTarget(
      self.snmpEngine, 'sendShutdownTrap', 'my-filter', 'managers', 'trap'
    )

    # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
    # and SecurityName
    config.addContext(self.snmpEngine, '')
    config.addVacmUser(self.snmpEngine, 1, 'Arduino', 'noAuthNoPriv',
                       (), (), (1,3,6))

    # *** SNMP engine configuration is complete by this line ***

    # Create default SNMP context where contextEngineId == SnmpEngineId
    snmpContext = context.SnmpContext(self.snmpEngine)

    if criticalStatus:
      self.trap=temperatureCritical
    else:
      self.trap=temperatureOK
      
    # Create Notification Originator App instance.
    ntforg.NotificationOriginator.__init__(self,snmpContext)
Exemple #23
0
def connect_to_server():
    global snmpEngine
    snmpEngine = engine.SnmpEngine()
    # GUI變數
    ip_addr = ip_entry.get()
    port_num = port_entry.get()
    global model_name
    model_name = model_combo.get() + "-MIB"

    # Setup UDP over IPv4 transport endpoint
    config.addTransport(
        snmpEngine, udp.domainName,
        udp.UdpTransport().openServerMode((ip_addr, int(port_num))))

    # SNMPv2c setup
    # "my-area" -> user name / "public" -> community name
    config.addV1System(snmpEngine, "my-area", "public")

    config.addContext(snmpEngine, "")

    # Allow full MIB access for this user / securityModels at VACM
    config.addVacmUser(snmpEngine, 2, "my-area", "noAuthNoPriv",
                       (1, 3, 6, 1, 4, 1, 8691))

    # Create an SNMP context
    snmpContext = context.SnmpContext(snmpEngine)

    # Create MIB builder
    global mibBuilder
    mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder

    # Optionally set an alternative path to compiled MIBs
    print("Setting MIB sources...")
    MIBDIR = r"./pwd/mibfiles/"
    mibBuilder.addMibSources(builder.DirMibSource(MIBDIR))
    print("done")

    # Load modules
    print("Loading MIB modules...")
    mibBuilder.loadModules(model_name)
    """
    print("Indexing MIB objects..."),
    mibView = view.MibViewController(mibBuilder)
    print(mibView.getNodeName((1, 3, 6, 1, 4, 1, 8691, 2, 19, 1, 6, 4, 1, 1, 0)))
    print("done")
    """

    # Build mib tree
    print("Building MIB tree...")
    global mibInstrum
    mibInstrum = snmpContext.getMibInstrum()
    print("done")

    print("Building table entry index from human-friendly representation...")
    global portEntry
    portEntry, = mibBuilder.importSymbols(model_name, "portEntry")
    """
    networkConnEntry, = mibBuilder.importSymbols(
        model_name, "modbusProtocolEntry"
    )
    """

    global MibScalarInstance
    MibScalarInstance, = mibBuilder.importSymbols("SNMPv2-SMI",
                                                  "MibScalarInstance")

    global power1InputStatus, power2InputStatus
    power1InputStatus, = mibBuilder.importSymbols(model_name,
                                                  "power1InputStatus")
    power2InputStatus, = mibBuilder.importSymbols(model_name,
                                                  "power2InputStatus")
    print("done")
    """
    # Modify mibscalar value

    class Mypower1InputStatus(MibScalarInstance):
        # noinspection PyUnusedLocal
        def readGet(self, name, *args):
            # Just return a custom value
            return name, self.syntax.clone(power1InputStatus_Value.get())
    class Mypower2InputStatus(MibScalarInstance):
        # noinspection PyUnusedLocal
        def readGet(self, name, *args):
            # Just return a custom value
            return name, self.syntax.clone(power2InputStatus_Value.get())

    _power1InputStatus = Mypower1InputStatus(
        power1InputStatus.name, (0,), power1InputStatus.syntax
    )
    _power2InputStatus = Mypower2InputStatus(
        power2InputStatus.name, (0,), power2InputStatus.syntax
    )

    
    failedLoginLockedTime = MibScalarInstance(
        failedLoginLockedTime.name, (1, 3, 6, 1, 4, 1, 8691, 2, 19, 1, 6, 4, 1, 12, 0),
        failedLoginLockedTime.syntax.clone(50)
    )
    print(failedLoginLockedTime)
    

    # Register Managed Object with a MIB tree
    mibBuilder.exportSymbols(
        # "__" prefixed MIB modules take precedence on indexing
        model_name,
        _power1InputStatus=_power1InputStatus,
        _power2InputStatus=_power2InputStatus
    )
    """

    print("Getting instance ID")
    global instanceId
    instanceId = portEntry.getInstIdFromIndices(10)
    print("done")

    write_var()
    """
    # Modify mibtable value
    print("Create/update MOXA-NPS9450-MIB::consoleSetting table row: ")
    varBinds = mibInstrum.writeVars(
        ((portEntry.name + (2,) + instanceId, port_status),)
    )

    #mibInstrum.writeVars(((networkConnEntry.name + (2,) + instanceId_networkConnEntry, "0"),))
    #mibInstrum.writeVars(((realComEntry.name + (1,) + instanceId,"4"),))

    for oid, val in varBinds:
        print("%s = %s" % (".".join([str(x) for x in oid]), not val.isValue and "N/A" or val.prettyPrint()))
    print("done")

    print("Read whole MIB (table walk)")
    oid, val = (), None
    while True:
        oid, val = mibInstrum.readNextVars(((oid, val),))[0]
        if exval.endOfMib.isSameTypeWith(val):
            break
        print("%s = %s\n" % (".".join([str(x) for x in oid]), not val.isValue and "N/A" or val.prettyPrint()))
    print("done")
    """

    # Register SNMP Applications at the SNMP engine for particular SNMP context
    cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
    cmdrsp.SetCommandResponder(snmpEngine, snmpContext)
    cmdrsp.NextCommandResponder(snmpEngine, snmpContext)
    cmdrsp.BulkCommandResponder(snmpEngine, snmpContext)

    # Register an imaginary never-ending job to keep I/O dispatcher running forever
    snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish

    global connect_first
    # Run I/O dispatcher which would receive queries and send responses
    try:
        print("here")
        connect_first = 1
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        print("there")
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
Exemple #24
0
# to what targets (chosen by tag) and with what credentials.
#
config.addNotificationTarget(
    #    snmpEngine, 'my-notification', 'my-creds', 'all-my-managers', 'trap'
    snmpEngine,
    'my-notification',
    'my-creds',
    'all-my-managers',
    'inform')

#
# Notifications carry potentially confidential information from
# the Agent. Therefore access control is to be setup allowing
# NotificationOriginator access to certain portions of Agent MIB.
#
config.addContext(snmpEngine, '')
# SNMPv1
config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
# SNMPv2c
config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6))
# SNMPv3
config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1, 3, 6))
config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authPriv', (), (),
                   (1, 3, 6))
config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'authPriv', (), (),
                   (1, 3, 6))
config.addVacmUser(snmpEngine, 3, 'usr-md5-aes192', 'authPriv', (), (),
                   (1, 3, 6))
config.addVacmUser(snmpEngine, 3, 'usr-md5-aes256', 'authPriv', (), (),
                   (1, 3, 6))
config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (), (),
Exemple #25
0
def trigger_trap(temp):
	# Create SNMP engine instance
	snmpEngine = engine.SnmpEngine()

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

	# Specify security settings per SecurityName (SNMPv2c -> 1)
	config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1)

	# Setup transport endpoint and bind it with security settings yielding
	# a target name
	config.addSocketTransport(
	    snmpEngine,
	    udp.domainName,
	    udp.UdpSocketTransport().openClientMode()
	)
	config.addTargetAddr(
	    snmpEngine, 'my-nms',
	    udp.domainName, ('34.215.95.184', 162),
	    'my-creds',
	    tagList='all-my-managers'
	)

	# Specify what kind of notification should be sent (TRAP or INFORM),
	# to what targets (chosen by tag) and what filter should apply to
	# the set of targets (selected by tag)
	config.addNotificationTarget(
	    snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap'
	)

	# Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel
	# and SecurityName
	config.addContext(snmpEngine, '')
	config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1,3,6))

	# *** SNMP engine configuration is complete by this line ***

	# Create default SNMP context where contextEngineId == SnmpEngineId
	snmpContext = context.SnmpContext(snmpEngine)

	# Create Notification Originator App instance.
	ntfOrg = ntforg.NotificationOriginator(snmpContext)

	# Build and submit notification message to dispatcher
	ntfOrg.sendNotification(
	    snmpEngine,
	    # Notification targets
	    'my-notification',
	    # Trap OID (SNMPv2-MIB::coldStart)
	    #(1,3,6,1,6,3,1,1,5,1),
            (1,3,6,1,4,1,8072,2,7,1,1,1,1,3,1),
	    # ( (oid, value), ... )
	    ( ((1,3,6,1,4,1,8072,2,7,1,1,1,1,3,1), v2c.OctetString(temp)),
            ((1,3,6,1,2,1,1,5,0), v2c.OctetString('Reason: Admin brought down')) )
	)

	print('Notification is scheduled to be sent')

	# Run I/O dispatcher which would send pending message and process response
	snmpEngine.transportDispatcher.runDispatcher()