예제 #1
0
    def _getSession(self, content):
        traphost = content['action_destination']
        port = content.get('port', 162)
        destination = '%s:%s' % (traphost, port)

        if not traphost or port <= 0:
            log.error("%s: SNMP trap host information %s is incorrect ", destination)
            return None

        community = content.get('community', 'public')
        version = content.get('version', 'v2c')

        session = self._sessions.get(destination, None)
        if session is None:
            log.debug("Creating SNMP trap session to %s", destination)

            # Test that the hostname and port are sane.
            try:
                getaddrinfo(traphost, port)
            except Exception:
                raise ActionExecutionException("The destination %s is not resolvable." % destination)

            session = netsnmp.Session((
                '-%s' % version,
                '-c', community,
                destination)
            )
            session.open()
            self._sessions[destination] = session

        return session
예제 #2
0
    def __init__(
            self, taskName, configId, scheduleIntervalSeconds=3600,
            taskConfig=None):
        BaseTask.__init__(
            self, taskName, configId, scheduleIntervalSeconds, taskConfig
        )
        self.log = log

        # Needed for interface
        self.name = taskName
        self.configId = configId
        self.state = TaskStates.STATE_IDLE
        self.interval = scheduleIntervalSeconds
        self._daemon = getUtility(ICollector)
        self._eventService = queryUtility(IEventService)
        self._preferences = self._daemon
        self._statService = queryUtility(IStatisticsService)
        # For compatibility with captureReplay
        self.options = self._daemon.options
        self.oidMap = self._daemon.oidMap
        self.stats = Stats()

        # Command-line argument sanity checking
        self.processCaptureReplayOptions()
        self.session = None
        self._replayStarted = False
        if not self.options.replayFilePrefix:
            trapPort = self._preferences.options.trapport
            if not self.options.useFileDescriptor and trapPort < 1024:
                listen_ip = "ipv6" if ipv6_is_enabled() else "0.0.0.0"
                # Makes call to zensocket here
                # does an exec* so it never returns
                self._daemon.openPrivilegedPort(
                    '--listen',
                    '--proto=udp',
                    '--port=%s:%d' % (listen_ip, trapPort)
                )
                self.log("Unexpected return from openPrivilegedPort. Exiting.")
                sys.exit(1)

            # Start listening for SNMP traps
            self.log.info("Starting to listen on SNMP trap port %s", trapPort)
            self.session = netsnmp.Session()
            listening_protocol = "udp6" if ipv6_is_enabled() else "udp"
            if self._preferences.options.useFileDescriptor is not None:
                # open port 1162, but then dup fileno onto it
                listening_address = listening_protocol + ':1162'
                fileno = int(self._preferences.options.useFileDescriptor)
            else:
                listening_address = '%s:%d' % (listening_protocol, trapPort)
                fileno = -1
            self._pre_parse_callback = _pre_parse_factory(self._pre_parse)
            debug = self.log.isEnabledFor(logging.DEBUG)
            self.session.awaitTraps(
                listening_address, fileno, self._pre_parse_callback, debug
            )
            self.session.callback = self.receiveTrap
            twistedsnmp.updateReactor()
예제 #3
0
    def get(self, oid):
        """Synchronous get implementation"""

        self.session = netsnmp.Session(version=self._version,
                                       timeout=int(self.timeout * 1e6),
                                       retries=int(self.retries - 1),
                                       peername='%s:%d' % (self.ip, self.port),
                                       community=self.community,
                                       community_len=len(self.community),
                                       cmdLineArgs=self.cmdLineArgs)
        oid = tuple(map(int, oid.strip('.').split('.')))
        self.session.open()
        try:
            return self.session.sget([oid])
        finally:
            self.session.close()
예제 #4
0
    def snmpInform(self, addr, pdu):
        """
        A SNMP trap can request that the trap recipient return back a response.
        This is where we do that.
        """
        reply = netsnmp.lib.snmp_clone_pdu(c.byref(pdu))
        if not reply:
            self.log.error("Could not clone PDU for INFORM response")
            raise RuntimeError("Cannot respond to INFORM PDU")
        reply.contents.command = netsnmp.SNMP_MSG_RESPONSE
        reply.contents.errstat = 0
        reply.contents.errindex = 0

        # FIXME: might need to add udp6 for IPv6 addresses
        sess = netsnmp.Session(peername='%s:%d' % tuple(addr),
                               version=pdu.version)
        sess.open()
        if not netsnmp.lib.snmp_send(sess.sess, reply):
            netsnmp.lib.snmp_sess_perror("Unable to send inform PDU",
                                         self.session.sess)
            netsnmp.lib.snmp_free_pdu(reply)
        sess.close()
예제 #5
0
    def _getSession(self, content):
        """
        Override to build an SNMPv3 Session
        """

        ###
        # Get configs

        traphost = content['action_destination']
        port = content.get('port', 162)
        destination = '{}:{}'.format(traphost, port)
        if not traphost or port <= 0:
            log.error("%s: SNMP trap host information %s is incorrect ", destination)
            return None

        contextName = content['contextName']
        securityEngineId = content['securityEngineId']
        contextEngineId = content['contextEngineId']
        securityName = content['securityName']
        securityPassphrase = content['securityPassphrase']
        privacyPassphrase = content['privacyPassphrase']
        authProto = content['authProto'] if content['authProto'] != "None" else None
        privProto = content['privProto'] if content['privProto'] != "None" else None

        version = 'v3'

        usingAuth = False
        usingPriv = False

        ###
        # Build Session

        args = ('-%s' % version, )
        if contextName:
            args += ( '-n', contextName)
        if securityEngineId:
            args += ('-e', securityEngineId)
        if contextEngineId:
            args += ('-E', contextEngineId)
        args += ( '-u', securityName)
        if authProto:
            usingAuth = True
            args += (
                '-a', authProto,
                '-A', securityPassphrase,
            )
        if privProto:
            usingPriv = True
            args += (
                '-x', privProto,
                '-X', privacyPassphrase,
            )
        securityLevel = 'noAuthNoPriv'
        if usingAuth:
            if usingPriv:
                securityLevel = 'authPriv'
            else:
                securityLevel = 'authNoPriv'
        args += (
            '-l', securityLevel,
            destination
        )

        session = netsnmp.Session(args)
        agent_addr = os.getenv('CONTROLPLANE_HOST_IPS', '').split(' ')[0]
        if agent_addr:
            session.agent_addr = agent_addr
        session.open()

        return session