Esempio n. 1
0
    def traprcv(self):
        """Create SNMP engine with autogenernated engineID and pre-bound to socket transport dispatcher"""
        snmpEngine = engine.SnmpEngine()

        """Transport setup  # UDP over IPv4, first listening interface/port"""
        config.addTransport(
            snmpEngine,
            udp.domainName + (1,),
            udp.UdpTransport().openServerMode((self.hosta, self.porta))
        )

        """UDP over IPv4, second listening interface/port"""
        config.addTransport(
            snmpEngine,
            udp.domainName + (2,),
            udp.UdpTransport().openServerMode((self.hostb, self.portb))
        )

        """SNMPv1/2c setup # SecurityName <-> CommunityName mapping"""
        config.addV1System(snmpEngine, 'my-area', 'public')

        """Register SNMP Application at the SNMP engine"""
        ntfrcv.NotificationReceiver(snmpEngine, self.cbFun)
        """this job would never finish"""
        snmpEngine.transportDispatcher.jobStarted(1)

        """Run I/O dispatcher which would receive queries and send confirmations"""
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except IOError:
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
        finally:
            pass
Esempio n. 2
0
def receiveTraps():  #checks for incoming traps
    try:
        snmpEngine = SnmpEngine()
        TrapAgentAddress = 'localhost'
        Port = 162

        print("Now listening for Trap on " + TrapAgentAddress + ":" +
              str(Port) + "...\n")
        config.addTransport(
            snmpEngine, udp.domainName + (1, ),
            udp.UdpTransport().openServerMode((TrapAgentAddress, Port)))

        config.addV1System(snmpEngine, 'community', 'public')

        def trapOutput(snmpEngine, stateReference, contextEngineId,
                       contextName, varBinds, cbCtx):
            print("Received new Trap message")
            for name, val in varBinds:  #iterates through each received oid pair
                print('%s = %s' %
                      (name.prettyPrint(),
                       val.prettyPrint()))  #pretty Print to make it readable
            return

        ntfrcv.NotificationReceiver(snmpEngine, trapOutput)

        snmpEngine.transportDispatcher.jobStarted(1)
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except:
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
    except KeyboardInterrupt:
        return
Esempio n. 3
0
    def _setup(self):
        """ Setup Server """
        assert isinstance(self._callbacks, list), \
            "callbacks should be list of functions type not %s" % type(
                self._callbacks)

        snmp_engine = engine.SnmpEngine()
        build = snmp_engine.getMibBuilder()

        if self._add_mib_dir:
            if not os.path.exists(self._add_mib_dir):
                raise PiatError("mib dir does not exist, dir=%r" %
                                self._add_mib_dir)
            if not os.path.isdir(self._add_mib_dir):
                raise PiatError(
                    "add_mib_dir should be a directory not a file, add_mib_dir=%r"
                    % self._add_mib_dir)
            build.addMibSources(builder.DirMibSource(self._add_mib_dir))

        build.loadModules()
        viewer = view.MibViewController(build)
        # UDP over IPv4, first listening interface/port
        transport = udp.UdpTransport()
        config.addTransport(snmp_engine, udp.domainName + (1, ),
                            transport.openServerMode(('0.0.0.0', self._port)))
        # SecurityName <-> CommunityName mapping
        config.addV1System(snmp_engine, '????', self._community)
        # Register SNMP Application at the SNMP engine
        handler = TrapsHandler(self._callbacks, viewer)
        ntfrcv.NotificationReceiver(snmp_engine, handler.handle)
        self._snmpEngine = snmp_engine
Esempio n. 4
0
def initialize_snmp_listener(community, port):

    # Bind SNMP to socket transport dispatcher
    snmpEngine = engine.SnmpEngine()

    # Transport setup
    # UDP over IPv4, first listening interface/port
    config.addTransport(snmpEngine, udp.domainName + (1, ),
                        udp.UdpTransport().openServerMode(('0.0.0.0', port)))
    logger.debug(f'listening on port: {port} - the standard port is 162')

    # SNMPv1/2c setup
    # SecurityName <-> CommunityName mapping
    config.addV1System(snmpEngine, 'my-area', community)

    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmpEngine, handle_mac_notification)

    snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish

    # Run I/O dispatcher which would receive queries and send confirmations
    try:
        logger.debug(f"SNMP Engine running")
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        logger.debug(f"SNMP Engine failure ")
        raise
Esempio n. 5
0
def add_transport(snmpEngine, PORT, ip_type):
    """

    :param snmpEngine:

    :return:

    """

    try:

        if ip_type == '6':

            config.addTransport(
                snmpEngine, udp.domainName,
                udp6.Udp6SocketTransport().openServerMode(('::', int(PORT))))

        else:

            config.addTransport(
                snmpEngine, udp.domainName,
                udp.UdpTransport().openServerMode(('0.0.0.0', int(PORT))))

    except error.CarrierError as excep:

        print "Port Binding Failed the Provided Port {} is in Use".format(PORT)
Esempio n. 6
0
 def setup_transport(self):
     transport_domain = udp.domainName + (self.engine_id,)
     self.engine.registerTransportDispatcher(self.transport_dispatcher,
                                             transport_domain)
     config.addTransport(self.engine, transport_domain,
                         udp.UdpTransport().openServerMode(
                             (self.ip, self.port)))
Esempio n. 7
0
def run_trap_listener():
    if not traffy_config.ENABLE_SNMP:
        print("SNMP not enabled! Exiting...")
        exit()

    if not traffy_config.ENABLE_TRAP:
        print("Trap not enabled! Exiting...")
        exit()

    snmp_engine = engine.SnmpEngine()
    config.addTransport(
        snmp_engine, udp.domainName,
        udp.UdpTransport().openServerMode(
            ("0.0.0.0", traffy_config.TRAP_PORT)))

    for id in traffy_config.SWITCHES:
        config.addV3User(snmp_engine,
                         traffy_config.SWITCHES[id]["username"],
                         config.usmHMACSHAAuthProtocol,
                         traffy_config.SWITCHES[id]["password"],
                         config.usmDESPrivProtocol,
                         traffy_config.SWITCHES[id]["password"],
                         securityEngineId=v2c.OctetString(
                             hexValue=traffy_config.SWITCHES[id]["engine_id"]))

    ntfrcv.NotificationReceiver(snmp_engine, trap_callback)
    snmp_engine.transportDispatcher.jobStarted(1)

    try:
        snmp_engine.transportDispatcher.runDispatcher()
    except:
        snmp_engine.transportDispatcher.closeDispatcher()
Esempio n. 8
0
    def _addEndpoint(self, addr):
        f = lambda h, p=161: (h, int(p))

        try:
            h, p = f(*addr.split(':'))

        except Exception:
            raise SnmpsimError('improper IPv4/UDP endpoint %s' % addr)

        return udp.UdpTransport().openServerMode((h, p)), addr
Esempio n. 9
0
 def _add_transport(self):
     """Configures the transport parameters for the snmp engine."""
     try:
         config.addTransport(
             self.snmp_engine, udp.domainName,
             udp.UdpTransport().openServerMode(
                 (self.trap_receiver_address,
                  int(self.trap_receiver_port))))
     except Exception:
         raise ValueError("Port binding failed: Port is in use.")
Esempio n. 10
0
 def _add_transport(self):
     """Configures the transport parameters for the snmp engine."""
     try:
         config.addTransport(
             self.snmp_engine,
             udp.domainName,
             udp.UdpTransport().openServerMode(
                 (self.trap_receiver_address, int(self.trap_receiver_port)))
         )
     except Exception as e:
         LOG.error('Failed to add transport, error is %s'
                   % six.text_type(e))
         raise exception.DelfinException(message=six.text_type(e))
Esempio n. 11
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
Esempio n. 12
0
    def __init__(self, ip, port, community='public'):

        self.LISTENER = ip
        self.LISTENER_PORT = port
        self.snmpEngine = engine.SnmpEngine()
        self.trap_sources = []
        self.community = community
        self.traps = {}
        config.addTransport(
            self.snmpEngine, udp.domainName + (1, ),
            udp.UdpTransport().openServerMode(
                (self.LISTENER, self.LISTENER_PORT)))
        print('Starting SNMP server on %s port %s with community %s.' %
              (self.LISTENER, self.LISTENER_PORT, community))
        config.addV1System(self.snmpEngine, 'testindex', community)
        self.stopped = False
Esempio n. 13
0
def trap_receiver():

    myAddress = socket.gethostbyname(socket.gethostname())
    snmpEngine = engine.SnmpEngine()
    TrapAgentAddress = myAddress
    Port = 162
    config.addTransport(
        snmpEngine, udp.domainName + (1, ),
        udp.UdpTransport().openServerMode((TrapAgentAddress, Port)))
    config.addV1System(snmpEngine, 'my-area', 'public')
    ntfrcv.NotificationReceiver(snmpEngine, cbFun)
    snmpEngine.transportDispatcher.jobStarted(1)
    try:
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
 def create_trap_listner_job(cls, port="162"):
     """
     Create Trap listner job
     :param port:
     :return:None
     """
     mibBuilder = builder.MibBuilder()
     custom_mib_path = cls.data_repo.get("custom_mib_path")
     load_mib_module = cls.data_repo.get("load_mib_module")
     temp_custom_mib_paths = []
     if custom_mib_path and load_mib_module:
         custom_mib_paths = custom_mib_path.split(',')
         for paths in custom_mib_paths:
             paths = paths.strip()
             if 'http' in paths and '@mib@' not in paths:
                 if paths[-1] == '/':
                     paths = paths + '/@mib@'
                 else:
                     paths = paths + '@mib@'
             if 'http' in paths and 'browse' in paths:
                 paths = paths.replace('browse', 'raw')
             if 'http' in paths and 'browse' in paths:
                 paths = paths.replace('browse', 'raw')
             temp_custom_mib_paths.append(paths)
         if os.name == 'posix' and '/usr/share/snmp/' not in custom_mib_path:
             temp_custom_mib_paths.append('/usr/share/snmp/')
         try:
             compiler.addMibCompiler(mibBuilder,
                                     sources=temp_custom_mib_paths)
             cls.mibViewController = view.MibViewController(mibBuilder)
             mibs = load_mib_module.split(",")
             mibBuilder.loadModules(*mibs)
         except error.MibNotFoundError as excep:
             testcase_Utils.pNote("{} Mib Not Found!".format(excep),
                                  "Error")
     snmpEngine = cls.get_asyncoredispatcher(port)
     udptransport = udp.UdpTransport()
     cls.udptransport.update({"udptransport{}".format(port): udptransport})
     config.addTransport(
         snmpEngine, udp.domainName,
         udptransport.openServerMode(('0.0.0.0', int(port))))
     snmpEngine.transportDispatcher.jobStarted(1)
Esempio n. 15
0
    def __init__(self, out_q):
        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher
        snmpEngine = engine.SnmpEngine()

        # Transport setup

        # UDP over IPv4, first listening interface/port
        config.addTransport(snmpEngine, udp.domainName + (1, ),
                            udp.UdpTransport().openServerMode((IP, 162)))

        # SNMPv1/2c setup

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

        # Callback function for receiving notifications
        # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
        def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
                  varBinds, cbCtx):
            print('Notification from ContextEngineId "%s", ContextName "%s"' %
                  (contextEngineId.prettyPrint(), contextName.prettyPrint()))
            for name, val in varBinds:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))

            out_q.put("teste")

        # Register SNMP Application at the SNMP engine
        if ntfrcv.NotificationReceiver(snmpEngine, cbFun):
            print "HEEEE"

        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
Esempio n. 16
0
def trap_engine():
    snmpEngine = engine.SnmpEngine()
    print('[SNMP API] Trap Server listening on ' + listening_ip + ":" +
          str(listening_port))
    config.addTransport(
        snmpEngine, udp.domainName + (1, ),
        udp.UdpTransport().openServerMode((listening_ip, listening_port)))
    config.addV1System(snmpEngine, 'my-area', 'public')

    def callback(eng, ref, eng_id, name, var_binds, cb_ctx):
        sender_domain, sender_address = eng.msgAndPduDsp.getTransportInfo(ref)
        if not trap_list.__contains__(sender_address[0]):
            trap_list.append(sender_address[0])

    ntfrcv.NotificationReceiver(snmpEngine, callback)
    snmpEngine.transportDispatcher.jobStarted(1)

    try:
        snmpEngine.transportDispatcher.runDispatcher()
    finally:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
Esempio n. 17
0
import redis

import redis
redis_store = redis.Redis(host=str(yaml_config['redis']['host']),
                          port=str(yaml_config['redis']['port']),
                          db=0)
# Create SNMP engine
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4
config.addTransport(
    snmpEngine, udp.domainName,
    udp.UdpTransport().openServerMode(
        (str(yaml_config['snmp']['listen_address']),
         int(yaml_config['snmp']['port']))))

# SNMPv3/USM setup

# user: usr-md5-none, auth: MD5, priv NONE
config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol,
                 'authkey1')
# Allow full MIB access for each user at VACM
config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv',
                   (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))

# SNMPv2c setup

# SecurityName <-> CommunityName mapping.
config.addV1System(snmpEngine, 'my-area', 'public')
Esempio n. 18
0
snmpEngine = engine.SnmpEngine()

TrapAgentAddress = '0.0.0.0'
#Trap listerner address
Port = 162
#trap listerner port

print("Agent is listening SNMP Trap on " + TrapAgentAddress + " , Port : " +
      str(Port))
print(
    '--------------------------------------------------------------------------'
)
config.addTransport(
    snmpEngine, udp.domainName + (1, ),
    udp.UdpTransport().openServerMode((TrapAgentAddress, Port)))

#Configure community here
config.addV1System(snmpEngine, 'my-area', 'public')


def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
          cbCtx):
    print("Received new Trap message")
    for name, val in varBinds:
        print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))


ntfrcv.NotificationReceiver(snmpEngine, cbFun)

snmpEngine.transportDispatcher.jobStarted(1)
Esempio n. 19
0
                        ])
mibViewController = view.MibViewController(mibBuilder)
# Pre-load MIB modules we expect to work with
try:
    mibBuilder.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB',
                           'SYSLOG-MSG-MIB')
except Exception:
    print("Failed loading MIBs")

# Create SNMP engine with autogenernated engineID and pre-bound to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup
# UDP over IPv4, add listening interface/port
config.addTransport(snmpEngine, udp.domainName + (1, ),
                    udp.UdpTransport().openServerMode((snmpip, snmpport)))

# SNMPv1/2c setup
# SecurityName <-> CommunityName mapping
config.addV1System(snmpEngine, 'my-area', 'public')

print("Started SNMP Trap Receiver: %s, %s, Output: %s" %
      (snmpport, snmpip, szOutputfile))
logFile.write("Started SNMP Trap Receiver: %s, %s, Output: %s" %
              (snmpport, snmpip, szOutputfile))
logFile.flush()


# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbReceiverSnmp(snmpEngine, stateReference, contextEngineId, contextName,
Esempio n. 20
0
# Instantiate and configure SNMP Engines
for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo:
    # Create SNMP engine with specific engineID
    snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue=snmpEngineId))

    # 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
Esempio n. 21
0
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
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
snmpEngine = engine.SnmpEngine()

# Transport setup

# 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')

#
# Transport setup
#

# Agent section

# UDP over IPv6
config.addTransport(snmpEngine, udp6.domainName,
                    udp6.Udp6Transport().openServerMode(('::1', 161)))

# Manager section

# UDP over IPv4
config.addTransport(snmpEngine, udp.domainName,
                    udp.UdpTransport().openClientMode())

#
# SNMPv1/2c setup (Agent role)
#

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

#
# SNMPv1/v2c setup (Manager role)
#
# Here we configure securityName lexicographically lesser than '1-my-area'
# to let it match first in snmpCommunityTable on response processing.
#
ErrorLog=clase_logFile.logApp(PATH_LOG)

print('\n{} Iniciando Auto_SNMPTrapReceiver'.format(datetime.now()));
ErrorLog.writeLog('Iniciando Auto_SNMPTrapReceiver')


try:
    dic_configuracion=InicializarDatos('config.ini')
    if dic_configuracion:
        
        # UDP over IPv4, first listening interface/port
        ErrorLog.writeLog('UDP over IPv4, first listening interface/port')
        config.addTransport(
            snmpEngine,
            udp.domainName + (1,),
            udp.UdpTransport().openServerMode((dic_configuracion.get('TrapAgentAddress'),
                                                dic_configuracion.get('Port')))
        )

        # SNMPv1/2c setup
        ErrorLog.writeLog('SNMPv1/2c setup')
        config.addV1System(snmpEngine,  dic_configuracion.get('CommunityName'), 
                                        dic_configuracion.get('ModeCommunity'))
        
    else:
        ErrorLog.writeLog('Inicializar Datos - Vacio por datos sin configurar')
except Exception as err:
    print("Error: {}".format(err))
    ErrorLog.writeLog("Error: {}".format(err))
else: 
    print('--------------------------------------------------------------------------')
    print('Start SNMPTrapReceiver -> {}'.format(datetime.now()))
Esempio n. 24
0
"""#
import pymongo
import datetime
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv

# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4, first listening interface/port
config.addTransport(snmpEngine, udp.domainName + (1, ),
                    udp.UdpTransport().openServerMode(('10.0.27.2', 162)))

# UDP over IPv4, second listening interface/port
config.addTransport(snmpEngine, udp.domainName + (2, ),
                    udp.UdpTransport().openServerMode(('10.0.27.2', 2162)))

# SNMPv1/2c setup

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


# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
          cbCtx):
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv

# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4, first listening interface/port
config.addTransport(snmpEngine, udp.domainName + (1, ),
                    udp.UdpTransport().openServerMode(('192.168.56.1', 162)))

# UDP over IPv4, second listening interface/port
# config.addTransport(
#     snmpEngine,
#     udp.domainName + (2,),
#     udp.UdpTransport().openServerMode(('192.168.56.1', 2162))
# )

# SNMPv1/2c setup

# SecurityName <-> CommunityName mapping
config.addV1System(snmpEngine, 'debianEdet', 'debianEdet')


# Callback function for receiving notifications
def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds,
          cbCtx):
    print('Notification from ContextEngineId "%s", ContextName "%s"' %
Esempio n. 26
0
writeLogs(len(outstring) * '~' + '\n' + outstring + '\n' + len(outstring) * '~')
print('Now listening for traps ...')


# 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(('0.0.0.0', 1161))
)

# SNMPv3/USM setup

config.addV3User(
    snmpEngine, userConfig['DEFAULT']['SNMPUSER'],
    config.usmHMAC128SHA224AuthProtocol, userConfig['DEFAULT']['SNMPAUTH'],
    config.usmAesCfb192Protocol, userConfig['DEFAULT']['SNMPPRIV'],
    securityEngineId=v2c.OctetString(hexValue='0102030405060708')
)


# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
Esempio n. 27
0
"""#
from pysnmp.entity import engine, config
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv

# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4, first listening interface/port
config.addTransport(
    snmpEngine,
    udp.DOMAIN_NAME + (1,),
    udp.UdpTransport().openServerMode(('127.0.0.1', 162))
)

# UDP over IPv4, second listening interface/port
config.addTransport(
    snmpEngine,
    udp.DOMAIN_NAME + (2,),
    udp.UdpTransport().openServerMode(('127.0.0.1', 2162))
)

# SNMPv1/2c setup

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

Esempio n. 28
0
    def engine(self):
        """
        Setup SNMP engine and context
        """
        log = 'SNMP agent engine initialization sequence begun.  ' +\
              'This may take a minute or two.'
        logger.info(log)
        print(log)
        MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log])

        # Create SNMP engine with auto generated engineID and pre-bound
        # to socket transport dispatcher
        self.eng_snmp = engine.SnmpEngine()

        # Transport setup

        # UDP over IPv4 at 0.0.0.0:8900
        config.addTransport(
            self.eng_snmp, udp.domainName,
            udp.UdpTransport().openServerMode(iface=('', 8900)))
        # UDP over IPv6 at [::]:8900
        config.addTransport(
            self.eng_snmp, udp6.domainName,
            udp6.Udp6Transport().openServerMode(iface=('::', 8900)))

        # SNMPv2c setup

        # SecurityName <-> CommunityName mapping.
        config.addV1System(snmpEngine=self.eng_snmp,
                           communityIndex='agent',
                           communityName='janusess')
        # Allow full MIB access for this user / securityModels at VACM
        # MIB 1.3.6.1.4.1.9934 refers to Janus Research Group
        # MIB 1.3.6.1.4.1.9934.0 refers to JanusESS Project
        config.addVacmUser(snmpEngine=self.eng_snmp,
                           securityModel=2,
                           securityName='agent',
                           securityLevel='noAuthNoPriv',
                           readSubTree=(1, 3, 6, 1, 4, 1, 9934, 0))

        # Get default SNMP context this SNMP engine serves
        self.ctx_snmp = context.SnmpContext(snmpEngine=self.eng_snmp)

        # Create custom Managed Object Instance
        self.mib_builder = self.ctx_snmp.getMibInstrum().getMibBuilder()
        mib_sources = self.mib_builder.getMibSources() + \
            (
                builder.DirMibSource('/opt/Janus/ESS/python3/server/snmp/mibs'),
            )
        self.mib_builder.setMibSources(*mib_sources)

        # JANUS-MIB defines and locates all Janus Research Group projects
        # JANUSESS-MIB defines all JanusESS project entries
        self.mib_builder.loadModules('JANUS-MIB', 'JANUSESS-MIB')

        self.config_base()
        self.config_lane()
        self.config_module()
        self.config_sensor()

        # Register SNMP Applications at the SNMP engine for particular SNMP context
        cmdrsp.GetCommandResponder(self.eng_snmp, self.ctx_snmp)
        cmdrsp.NextCommandResponder(self.eng_snmp, self.ctx_snmp)
        cmdrsp.BulkCommandResponder(self.eng_snmp, self.ctx_snmp)

        dispatcher = threading.Thread(target=self.dispatcher, args=())
        dispatcher.start()
        MPQ_STAT.put_nowait(['snmp_agent', dispatcher.ident])

        log = 'SNMP agent engine sequence concluded.'
        logger.info(log)
        MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log])
        MPQ_STAT.put_nowait(['base', ['snmp_agent', STAT_LVL['op']]])

        log = 'SNMP agent listener started.'
        logger.info(log)
        print(log)
        MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log])

        # Poll SNMP agent queues for values to update variables
        while True:
            if not MPQ_SNMPA_STOP.empty():
                MPQ_SNMPA_STOP.get()
                self.eng_snmp.transportDispatcher.closeDispatcher()
                break

            if not MPQ_SNMPA2.empty():
                mpq_record = MPQ_SNMPA2.get()
                self.base(mpq_record=mpq_record)

            if not MPQ_SNMPA3.empty():
                mpq_record = MPQ_SNMPA3.get()
                self.lane(mpq_record=mpq_record)

            if not MPQ_SNMPA4.empty():
                mpq_record = MPQ_SNMPA4.get()
                self.module(mpq_record=mpq_record)

            if not MPQ_SNMPA5.empty():
                mpq_record = MPQ_SNMPA5.get()
                self.sensor(mpq_record=mpq_record)

            time.sleep(0.1)

        MPQ_STAT.put_nowait(['snmp_agent', False])
        log = 'SNMP agent dispatcher stopped.'
        logger.info(log)
        MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log])

        log = 'SNMP agent listener stopped.'
        logger.info(log)
        print(log)
        MPQ_ACT.put_nowait([datetime.now().isoformat(' '), 'INFO', log])
        MPQ_STAT.put_nowait(['base', ['snmp_agent', STAT_LVL['not_cfg']]])
"""#
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.smi import instrum, builder
from pysnmp.proto.api import v2c

# Create SNMP engine
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-md5-none, auth: MD5, priv NONE
config.addV3User(snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol,
                 'authkey1')

# Allow full MIB access for each user at VACM
config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv',
                   (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1))

# Create an SNMP context with ContextEngineId = 8000000001020304
snmpContext = context.SnmpContext(
    snmpEngine, contextEngineId=v2c.OctetString(hexValue='8000000001020304'))
Esempio n. 30
0
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv

IP = '192.168.1.11'

# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmpEngine = engine.SnmpEngine()

# Transport setup

# UDP over IPv4, first listening interface/port
config.addTransport(
    snmpEngine,
    udp.domainName + (1,),
    udp.UdpTransport().openServerMode((IP, 162))
)

# SNMPv1/2c setup

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


# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
          varBinds, cbCtx):
    print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(),
                                                                        contextName.prettyPrint()))
    for name, val in varBinds: