Exemple #1
0
    def run(self):
        super(SnmpParsingService, self).run()
        LOG.info("Vitrage SNMP Parsing Service - Starting...")

        transport_dispatcher = AsyncoreDispatcher()
        transport_dispatcher.registerRecvCbFun(self.callback_func)

        trans_udp = udp.UdpSocketTransport()
        udp_transport = \
            trans_udp.openServerMode(('0.0.0.0', self.listening_port))

        trans_udp6 = udp6.Udp6SocketTransport()
        udp6_transport = \
            trans_udp6.openServerMode(('::1', self.listening_port))

        transport_dispatcher.registerTransport(udp.domainName, udp_transport)
        transport_dispatcher.registerTransport(udp6.domainName, udp6_transport)
        LOG.info("Vitrage SNMP Parsing Service - Started!")

        transport_dispatcher.jobStarted(self.RUN_FOREVER)
        try:
            transport_dispatcher.runDispatcher()
        except Exception:
            LOG.error("Run transport dispatcher failed.")
            transport_dispatcher.closeDispatcher()
            raise
Exemple #2
0
def main():

    logging.basicConfig(filename='traps.log',
                        filemode='w',
                        level=logging.ERROR,
                        format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p')

    transportDispatcher = AsyncoreDispatcher()

    transportDispatcher.registerRecvCbFun(cbFun)

    # UDP/IPv4
    transportDispatcher.registerTransport(
        udp.domainName,
        udp.UdpSocketTransport().openServerMode(('0.0.0.0', 162)))

    # UDP/IPv6
    transportDispatcher.registerTransport(
        udp6.domainName,
        udp6.Udp6SocketTransport().openServerMode(('::1', 162)))

    ## Local domain socket
    # transportDispatcher.registerTransport(
    #    unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-manager')
    # )

    transportDispatcher.jobStarted(1)

    try:
        # Dispatcher will never finish as job#1 never reaches zero
        transportDispatcher.runDispatcher()
    except:
        transportDispatcher.closeDispatcher()
        raise
    def init_new_dispatcher(self, id_src):
        self.dict_dispatchers[id_src] = AsyncoreDispatcher()
        self.dict_dispatchers_locks[id_src] = _thread.allocate_lock()

        self.dict_dispatchers[id_src].registerRecvCbFun(self.cbRecvFun)
        self.dict_dispatchers[id_src].registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        self.dict_dispatchers[id_src].jobStarted(1)
def define_request(source, ip, community, snmp_version, fileconfname, pathfile,
                   protocol, srvprovision, enableconfstart, urlfirmware,
                   enablereboot):
    if snmp_version == '2c':
        communityData = CommunityData(community, mpModel=1)
    if snmp_version == '1':
        communityData = CommunityData(community, mpModel=0)
    if source:
        assd = AsynsockDispatcher()
        sock_transport = udp.UdpSocketTransport()
        sock_transport.socket.setsockopt(socket.SOL_SOCKET, 25, source + '\0')
        snmp_engine = engine.SnmpEngine()
        assd.registerTransport(udp.domainName, sock_transport)
        snmp_engine.registerTransportDispatcher(assd)
    else:
        snmp_engine = engine.SnmpEngine()
    varBind = []
    result = []
    for errorIndication, errorStatus, errorIndex, varBinds in setCmd(
            snmp_engine, communityData, UdpTransportTarget((ip, 161)),
            ContextData(),
            ObjectType(
                ObjectIdentity(
                    '1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.100.0'),
                OctetString(fileconfname)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.300.0'),
                OctetString(pathfile)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.100.0'),
                Integer32(protocol)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.400.0'),
                OctetString(srvprovision)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.500.100.0'),
                Integer32(enableconfstart)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.450.0'),
                OctetString(urlfirmware)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.500.0'),
                Integer32(enablereboot))):
        varBind.append(varBinds)
        for i in varBinds:
            i = str(i)
            i = i.split('=')[1]
            result.append(i)


#             result.append(str(i))
#             varBind = varBind.split('=')[1]
#             result.append(varBind)
    return result
Exemple #5
0
def escucharTrap():
    print("Escucho")
    # se queda escuchando, lanza callback (cb) cuando recibe paquyete
    transportDispatcher = AsyncoreDispatcher()

    transportDispatcher.registerRecvCbFun(cbFun)

    # UDP/IPv4
    transportDispatcher.registerTransport(
        udp.domainName,
        udp.UdpSocketTransport().openServerMode(('0.0.0.0', 162)))

    # UDP/IPv6
    transportDispatcher.registerTransport(
        udp6.domainName,
        udp6.Udp6SocketTransport().openServerMode(('::1', 162)))

    transportDispatcher.jobStarted(1)

    try:
        # Dispatcher will never finish as job#1 never reaches zero
        transportDispatcher.runDispatcher()
    except:
        transportDispatcher.closeDispatcher()

        raise
Exemple #6
0
    def listenForTraps(self):
        asyncF = asyncFunc()
        transportDispatcher = AsyncoreDispatcher()

        transportDispatcher.registerRecvCbFun(asyncF.cbFun)

        transportDispatcher.registerTransport(
            udp.domainName, udp.UdpSocketTransport().openServerMode((self.SNMP_HOST, self.SNMP_PORT))
        )

        transportDispatcher.jobStarted(1)

        try:
            # Dispatcher will never finish as job#1 never reaches zero
            transportDispatcher.runDispatcher()

        finally:
            transportDispatcher.closeDispatcher()
    def run(self):
        self.logger.info("Starting PDU '{}' on {}:{}".format(
            self.pdu.name, self.listen_address, self.listen_port))
        self.transportDispatcher.registerRecvCbFun(
            self.snmp_handler.message_handler)

        # UDP/IPv4
        self.transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openServerMode(
                (self.listen_address, self.listen_port)))

        self.transportDispatcher.jobStarted(1)

        try:
            # Dispatcher will never finish as job#1 never reaches zero
            self.transportDispatcher.runDispatcher()
        except Exception:
            self.transportDispatcher.closeDispatcher()
Exemple #8
0
def run_dispatcher(conf):
    transportDispatcher = AsyncoreDispatcher()
    transportDispatcher.registerRecvCbFun(callback)

    for num, cfg_string in enumerate(conf.alerts_interfaces):
        parsed = cfg_string.split(':')
        address = (parsed[0], int(parsed[1]) if len(parsed) == 2 else 162)
        transportDispatcher.registerTransport(
            udp.domainName + (num + 1, ),
            udp.UdpSocketTransport().openServerMode(address))

    transportDispatcher.jobStarted(1)

    try:
        # Dispatcher will never finish as job#1 never reaches zero
        transportDispatcher.runDispatcher()
    except:
        transportDispatcher.closeDispatcher()
    raise
Exemple #9
0
def createSNMP(host, community=None):
    if community is None:
        community = "public"

    ip = gethostbyname(host)
    snmpEngine = engine.SnmpEngine()
    config.addV1System(snmpEngine, 'my-area', community)
    config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv',
                           0)
    config.addTransport(snmpEngine, udp.domainName,
                        udp.UdpSocketTransport().openClientMode())
    config.addTargetAddr(snmpEngine, 'my-router', udp.domainName, (ip, 161),
                         'my-creds')

    cmdgen.NextCommandGenerator().sendVarBinds(
        snmpEngine, 'my-router', None, '',
        [((1, 3, 6, 1, 2, 1, 1, 0, 0), None)], getHost)
    snmpEngine.transportDispatcher.runDispatcher()

    cmdgen.NextCommandGenerator().sendVarBinds(
        snmpEngine, 'my-router', None, '',
        [((1, 3, 6, 1, 2, 1, 4, 34, 1, 3, 2, 16), None)], getAddrs)
    snmpEngine.transportDispatcher.runDispatcher()
Exemple #10
0
                encoder.encode(reqMsg), transportDomain, transportAddress
            )
            global startedAt
            if time() - startedAt > 3:
                raise Exception('Request timed out')
            startedAt = time()
    return wholeMsg
 
 
transportDispatcher = AsyncoreDispatcher()
 
transportDispatcher.registerRecvCbFun(cbRecvFun)
transportDispatcher.registerTimerCbFun(cbTimerFun)
 
transportDispatcher.registerTransport(
    udp.domainName, udp.UdpSocketTransport().openClientMode()
)
transportDispatcher.sendMessage(
    encoder.encode(reqMsg), udp.domainName, (input('Enter Host: '), 161)
)
transportDispatcher.jobStarted(1)
 
# Dispatcher will finish as job#1 counter reaches zero
transportDispatcher.runDispatcher()
 
transportDispatcher.closeDispatcher()from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pyasn1.codec.ber import encoder, decoder
from pysnmp.proto.api import v2c
from time import time
 
def snmpgetint(self, host, check):
    global checkname
    global hostname
    global res
    try:
        print('doing ' + check + ' on ' + host)
        hostname = Hosts.objects.get(name=host)
        if hostname.enabled is True:
            checkname = HostChecks.objects.get(name=check)
            address = hostname.address
            community = hostname.community
            oid = checkname.arg
            # res = str(float(snmp_get(oid, hostname=address, community=community, version=1).value) * float(check.quotient))
            # from pysnmp import debug
            # debug.setLogger(debug.Debug('msgproc'))

            # Protocol version to use
            pMod = api.protoModules[api.protoVersion1]
            # pMod = api.protoModules[api.protoVersion2c]

            # Build PDU
            reqPDU = pMod.GetRequestPDU()
            pMod.apiPDU.setDefaults(reqPDU)
            pMod.apiPDU.setVarBinds(reqPDU, (((oid), pMod.Null()), ))

            # Build message
            reqMsg = pMod.Message()
            pMod.apiMessage.setDefaults(reqMsg)
            pMod.apiMessage.setCommunity(reqMsg, community)
            pMod.apiMessage.setPDU(reqMsg, reqPDU)

            startedAt = time()

            def cbTimerFun(timeNow):
                if timeNow - startedAt > 3:
                    raise Exception("Request timed out")

            # noinspection PyUnusedLocal,PyUnusedLocal
            def cbRecvFun(transportDispatcher,
                          transportDomain,
                          transportAddress,
                          wholeMsg,
                          reqPDU=reqPDU):
                while wholeMsg:
                    rspMsg, wholeMsg = decoder.decode(wholeMsg,
                                                      asn1Spec=pMod.Message())
                    rspPDU = pMod.apiMessage.getPDU(rspMsg)
                    # Match response to request
                    if pMod.apiPDU.getRequestID(
                            reqPDU) == pMod.apiPDU.getRequestID(rspPDU):
                        # Check for SNMP errors reported
                        errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
                        if errorStatus:
                            print(errorStatus.prettyPrint())
                        else:
                            for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
                                # print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
                                # res = str(float(val.prettyPrint() * float(check.quotient)))
                                global checkname
                                global hostname
                                global res
                                res = str(
                                    float(val * float(checkname.quotient)))
                                computeint(checkname, hostname, res)
                        transportDispatcher.jobFinished(1)
                return wholeMsg

            transportDispatcher = AsyncoreDispatcher()

            transportDispatcher.registerRecvCbFun(cbRecvFun)
            # transportDispatcher.registerTimerCbFun(cbTimerFun)

            # UDP/IPv4
            transportDispatcher.registerTransport(
                udp.domainName,
                udp.UdpSocketTransport().openClientMode())

            # Pass message to dispatcher
            transportDispatcher.sendMessage(encoder.encode(reqMsg),
                                            udp.domainName, (address, 161))
            transportDispatcher.jobStarted(1)

            ## UDP/IPv6 (second copy of the same PDU will be sent)
            # transportDispatcher.registerTransport(
            #    udp6.domainName, udp6.Udp6SocketTransport().openClientMode()
            # )

            # Pass message to dispatcher
            # transportDispatcher.sendMessage(
            #    encoder.encode(reqMsg), udp6.domainName, ('::1', 161)
            # )
            # transportDispatcher.jobStarted(1)

            ## Local domain socket
            # transportDispatcher.registerTransport(
            #    unix.domainName, unix.UnixSocketTransport().openClientMode()
            # )
            #
            # Pass message to dispatcher
            # transportDispatcher.sendMessage(
            #    encoder.encode(reqMsg), unix.domainName, '/tmp/snmp-agent'
            # )
            # transportDispatcher.jobStarted(1)

            # Dispatcher will finish as job#1 counter reaches zero
            transportDispatcher.runDispatcher()

            transportDispatcher.closeDispatcher()
            # print(transportDispatcher)
            del transportDispatcher
            del pMod
            del reqPDU
            del reqMsg
            del startedAt
            del cbTimerFun
            del cbRecvFun

            # computeint(check, host, res)
            # print(oid + ' on ' + address + ' equals ' + res)
    except Exception as e:
        print('doing ' + checkname.name + ' on ' + hostname.name + ' failed')
        print(traceback.format_exc())
        # update the error count
        setMetadata(hostname.name + ':' + checkname.name + '::lasterror',
                    str(timezone.now()))
        setMetadata(
            hostname.name + ':' + checkname.name + '::nberror',
            int(
                getMetadata(hostname.name + ':' + checkname.name + '::nberror',
                            0)) + 1)
        # Log the error to the database.
        ErrorLog(hostcheck=checkname,
                 host=hostname,
                 event=e.__class__.__name__,
                 error=str(e),
                 value=res).save()
    return res
To respond from a non-local (e.g. spoofed) IP address, uncomment the
.enableTransparent() method call and run this script as root.

"""#
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asyncore.dgram import udp

# Create SNMP engine
snmpEngine = engine.SnmpEngine()

# Transport setup

# Initialize asyncore-based UDP/IPv4 transport
udpSocketTransport = udp.UdpSocketTransport().openServerMode(('0.0.0.0', 161))

# Use sendmsg()/recvmsg() for socket communication (used for preserving
# original destination IP address when responding)
udpSocketTransport.enablePktInfo()

# Enable IP source spoofing (requires root privileges)
# udpSocketTransport.enableTransparent()

# Register this transport at SNMP Engine
config.addTransport(snmpEngine, udp.DOMAIN_NAME, udpSocketTransport)

# SNMPv3/USM setup

# user: usr-md5-des, auth: MD5, priv DES
config.addV3User(snmpEngine, 'usr-md5-des', config.USM_AUTH_HMAC96_MD5,
Exemple #13
0
 def __init__(self, usage=False):
     # abort if pysnmp is not installed
     if not snmp_modules_found:
         output().warning_(
             "Please install the 'pysnmp' module for SNMP support.")
         if usage: print("")
         return
     # skip when running 'discover' in interactive mode
     if usage: print("No target given, discovering local printers")
     oid = (
         ('1.3.6.1.2.1.25.3.2.1.2.1',
          None),  # HOST-RESOURCES-MIB → hrDeviceType
         ('1.3.6.1.2.1.25.3.2.1.3.1',
          None),  # HOST-RESOURCES-MIB → hrDeviceDescr
         ('1.3.6.1.2.1.25.3.2.1.5.1',
          None),  # HOST-RESOURCES-MIB → hrDeviceStatus
         ('1.3.6.1.2.1.43.16.5.1.2.1.1',
          None),  # Printer-MIB        → Printer status
         ('1.3.6.1.2.1.1.3.0', None))  # SNMPv2-MIBv        → sysUpTime
     try:
         # build protocol data unit (pdu)
         pmod.apiPDU.setDefaults(pdu_send)
         pmod.apiPDU.setVarBinds(pdu_send, oid)
         # build message
         msg_send = pmod.Message()
         pmod.apiMessage.setDefaults(msg_send)
         pmod.apiMessage.setCommunity(msg_send, 'public')
         pmod.apiMessage.setPDU(msg_send, pdu_send)
         # ...
         dispatcher = AsyncoreDispatcher()
         dispatcher.registerRecvCbFun(recv)
         dispatcher.registerTimerCbFun(timer)
         # use ipv4 udp broadcast
         udpSocketTransport = udp.UdpSocketTransport().openClientMode(
         ).enableBroadcast()
         dispatcher.registerTransport(udp.domainName, udpSocketTransport)
         # pass message to dispatcher
         target = ('255.255.255.255', 161)
         dispatcher.sendMessage(encoder.encode(msg_send), udp.domainName,
                                target)
         # wait for timeout or max hosts
         dispatcher.jobStarted(1, maxhost)
         # dispatcher will finish as all jobs counter reaches zero
         try:
             dispatcher.runDispatcher()
         except stop_waiting:
             dispatcher.closeDispatcher()
         # list found network printers
         if results:
             print("")
             output().discover_(
                 ('address', ('device', 'uptime', 'status', None)))
             output().hline_(79)
             for printer in sorted(
                     results.items(),
                     key=lambda item: socket.inet_aton(item[0])):
                 output().discover_(printer)
         else:
             output().info_("No printers found via SNMP broadcast")
         if usage or results: print("")
     except Exception as e:
         output().errmsg_("SNMP Error", e)
         if usage: print("")
Exemple #14
0
# SecurityName <-> CommunityName mapping
config.addV1System(snmpEngine, 'my-area', 'public')

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

#
# Setup transport endpoint and bind it with security settings yielding
# a target name
#

# UDP/IPv4
config.addTransport(
    snmpEngine,
    udp.domainName,
    udp.UdpSocketTransport().openClientMode(('0.0.0.0', 61024))
)
config.addTargetAddr(
    snmpEngine, 'my-router',
    udp.domainName, ('104.236.166.95', 161),
    'my-creds'
)


# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, sendRequestHandle, errorIndication,
          errorStatus, errorIndex, varBindTable, cbCtx):
    if errorIndication:
        print(errorIndication)
        return
Exemple #15
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 #16
0
    def GEToutlet(self, outlet=None, IP=None):
        if IP == None:
            IP = self.ip
        pMod = api.protoModules[api.protoVersion1]
        # pMod = api.protoModules[api.protoVersion2c]
        # Build PDU
        reqPDU = pMod.GetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)
        pMod.apiPDU.setVarBinds(reqPDU, (
            (self.command['name'], pMod.Null('')),
            (self.command['port'], pMod.Null('')),
            (self.command['name_1'], pMod.Null('')),
            (self.command['name_2'], pMod.Null('')),
            (self.command['name_3'], pMod.Null('')),
            (self.command['name_4'], pMod.Null('')),
            (self.command['name_5'], pMod.Null('')),
            (self.command['name_6'], pMod.Null('')),
            (self.command['name_7'], pMod.Null('')),
            (self.command['name_8'], pMod.Null('')),
        ))

        # Build message
        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        startedAt = time()

        def cbTimerFun(timeNow):
            if timeNow - startedAt > 3:
                raise Exception("Request timed out")

        # noinspection PyUnusedLocal,PyUnusedLocal
        def cbRecvFun(transportDispatcher=None,
                      transportDomain=None,
                      transportAddress=None,
                      wholeMsg=None,
                      reqPDU=reqPDU):
            while wholeMsg:

                rspMsg, wholeMsg = decoder.decode(wholeMsg,
                                                  asn1Spec=pMod.Message())
                rspPDU = pMod.apiMessage.getPDU(rspMsg)
                # Match response to request
                if pMod.apiPDU.getRequestID(
                        reqPDU) == pMod.apiPDU.getRequestID(rspPDU):
                    # Check for SNMP errors reported
                    errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)

                    if errorStatus:
                        print(errorStatus.prettyPrint())
                    else:
                        for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
                            oid_str = oid.prettyPrint()

                            if oid_str == '1.3.6.1.4.1.318.1.1.4.2.2.0':
                                self.result_str = val.prettyPrint()

                            elif oid_str == self.command['name_1']:
                                self.nothing = []
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_2']:
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_3']:
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_4']:
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_5']:
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_6']:
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_7']:
                                self.nothing.append(val.prettyPrint())
                            elif oid_str == self.command['name_8']:
                                self.nothing.append(val.prettyPrint())

                transportDispatcher.jobFinished(1)
            return wholeMsg

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(cbRecvFun)
        transportDispatcher.registerTimerCbFun(cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openClientMode())

        # Pass message to dispatcher
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName,
                                        (IP, 161))
        transportDispatcher.jobStarted(1)

        # Dispatcher will finish as job#1 counter reaches zero
        transportDispatcher.runDispatcher()
        self.nothing = self.nothing + [
            '...',
            '...',
            '...',
            '...',
            '...',
            '...',
            '...',
            '...',
        ]
        #print self.nothing
        result_str = self.result_str.split()
        for i, element in enumerate(result_str):
            result_str[i] = '%d--%s--%s' % (i + 1, self.nothing[i],
                                            result_str[i])
        if outlet == None:
            for i in range(len(result_str)):
                print result_str[i]
        else:
            try:
                for j in outlet:
                    print result_str[int(j) - 1]
            except:
                print 'One outlet dosen\'t exist. Please check your input.'
        transportDispatcher.closeDispatcher()
        for f, i in pendingErrors:
            f(rspPDU, i)

        transportDispatcher.sendMessage(encoder.encode(rspMsg),
                                        transportDomain, transportAddress)

    return wholeMsg


transportDispatcher = AsyncoreDispatcher()
transportDispatcher.registerRecvCbFun(cbFun)

# UDP/IPv4
transportDispatcher.registerTransport(
    udp.DOMAIN_NAME,
    udp.UdpSocketTransport().openServerMode(('localhost', 161)))

# UDP/IPv6
transportDispatcher.registerTransport(
    udp6.DOMAIN_NAME,
    udp6.Udp6SocketTransport().openServerMode(('::1', 161)))

transportDispatcher.jobStarted(1)

try:
    # Dispatcher will never finish as job#1 never reaches zero
    transportDispatcher.runDispatcher()

except Exception:
    transportDispatcher.closeDispatcher()
    raise
Exemple #18
0
    def GETcurrent(self, IP=None):
        if IP == None:
            IP = self.ip
        pMod = api.protoModules[api.protoVersion1]

        # Build PDU
        reqPDU = pMod.GetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)
        pMod.apiPDU.setVarBinds(reqPDU,
                                ((self.command['current'], pMod.Null('')), ))

        # Build message
        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        startedAt = time()

        def cbTimerFun(timeNow):
            if timeNow - startedAt > 3:
                raise Exception("Request timed out")

        # noinspection PyUnusedLocal,PyUnusedLocal
        def cbRecvFun(transportDispatcher,
                      transportDomain,
                      transportAddress,
                      wholeMsg,
                      reqPDU=reqPDU):
            while wholeMsg:
                rspMsg, wholeMsg = decoder.decode(wholeMsg,
                                                  asn1Spec=pMod.Message())
                rspPDU = pMod.apiMessage.getPDU(rspMsg)
                # Match response to request
                if pMod.apiPDU.getRequestID(
                        reqPDU) == pMod.apiPDU.getRequestID(rspPDU):
                    # Check for SNMP errors reported
                    errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
                    if errorStatus:
                        print(errorStatus.prettyPrint())
                    else:
                        for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
                            oid_str = oid.prettyPrint()
                            if oid_str == '1.3.6.1.4.1.318.1.1.12.2.3.1.1.2.1':
                                print('%s' % (val.prettyPrint()))
                    transportDispatcher.jobFinished(1)
            return wholeMsg

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(cbRecvFun)
        transportDispatcher.registerTimerCbFun(cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openClientMode())

        # Pass message to dispatcher
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName,
                                        (IP, 161))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()

        transportDispatcher.closeDispatcher()
Exemple #19
0
def main():
    variation_module = None

    parser = argparse.ArgumentParser(description=DESCRIPTION)

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

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

    v1arch_group = parser.add_argument_group('SNMPv1/v2c parameters')

    v1arch_group.add_argument(
        '--protocol-version', choices=['1', '2c'],
        default='2c', help='SNMPv1/v2c protocol version')

    v1arch_group.add_argument(
        '--community', type=str, default='public',
        help='SNMP community name')

    v3arch_group = parser.add_argument_group('SNMPv3 parameters')

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

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

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

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

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

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

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

    parser.add_argument(
        '--use-getbulk', action='store_true',
        help='Use SNMP GETBULK PDU for mass SNMP managed objects retrieval')

    parser.add_argument(
        '--getbulk-repetitions', type=int, default=25,
        help='Use SNMP GETBULK PDU for mass SNMP managed objects retrieval')

    endpoint_group = parser.add_mutually_exclusive_group(required=True)

    endpoint_group.add_argument(
        '--agent-udpv4-endpoint', type=endpoints.parse_endpoint,
        metavar='<[X.X.X.X]:NNNNN>',
        help='SNMP agent UDP/IPv4 address to pull simulation data '
             'from (name:port)')

    endpoint_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 pull simulation data '
             'from ([name]:port)')

    parser.add_argument(
        '--timeout', type=int, default=3,
        help='SNMP command response timeout (in seconds)')

    parser.add_argument(
        '--retries', type=int, default=3,
        help='SNMP command retries')

    parser.add_argument(
        '--start-object', metavar='<MIB::Object|OID>', type=_parse_mib_object,
        default=univ.ObjectIdentifier('1.3.6'),
        help='Drop all simulation data records prior to this OID specified '
             'as MIB object (MIB::Object) or OID (1.3.6.)')

    parser.add_argument(
        '--stop-object', metavar='<MIB::Object|OID>',
        type=functools.partial(_parse_mib_object, last=True),
        help='Drop all simulation data records after this OID specified '
             'as MIB object (MIB::Object) or OID (1.3.6.)')

    parser.add_argument(
        '--mib-source', dest='mib_sources', metavar='<URI|PATH>',
        action='append', type=str,
        default=['http://mibs.snmplabs.com/asn1/@mib@'],
        help='One or more URIs pointing to a collection of ASN.1 MIB files.'
             'Optional "@mib@" token gets replaced with desired MIB module '
             'name during MIB search.')

    parser.add_argument(
        '--destination-record-type', choices=variation.RECORD_TYPES,
        default='snmprec',
        help='Produce simulation data with record of this type')

    parser.add_argument(
        '--output-file', metavar='<FILE>', type=str,
        help='SNMP simulation data file to write records to')

    parser.add_argument(
        '--continue-on-errors', metavar='<tolerance-level>',
        type=int, default=0,
        help='Keep on pulling SNMP data even if intermittent errors occur')

    variation_group = parser.add_argument_group(
        'Simulation data variation options')

    parser.add_argument(
        '--variation-modules-dir', action='append', type=str,
        help='Search variation module by this path')

    variation_group.add_argument(
        '--variation-module', type=str,
        help='Pass gathered simulation data through this variation module')

    variation_group.add_argument(
        '--variation-module-options', type=str, default='',
        help='Variation module options')

    args = parser.parse_args()

    if args.debug:
        pysnmp_debug.setLogger(pysnmp_debug.Debug(*args.debug))

    if args.debug_asn1:
        pyasn1_debug.setLogger(pyasn1_debug.Debug(*args.debug_asn1))

    if args.output_file:
        ext = os.path.extsep
        ext += variation.RECORD_TYPES[args.destination_record_type].ext

        if not args.output_file.endswith(ext):
            args.output_file += ext

        record = variation.RECORD_TYPES[args.destination_record_type]
        args.output_file = record.open(args.output_file, 'wb')

    else:
        args.output_file = sys.stdout

        if sys.version_info >= (3, 0, 0):
            # binary mode write
            args.output_file = sys.stdout.buffer

        elif sys.platform == "win32":
            import msvcrt

            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

    # Catch missing params

    if args.protocol_version == '3':
        if not args.v3_user:
            sys.stderr.write('ERROR: --v3-user is missing\r\n')
            parser.print_usage(sys.stderr)
            return 1

        if args.v3_priv_key and not args.v3_auth_key:
            sys.stderr.write('ERROR: --v3-auth-key is missing\r\n')
            parser.print_usage(sys.stderr)
            return 1

        if AUTH_PROTOCOLS[args.v3_auth_proto] == config.usmNoAuthProtocol:
            if args.v3_auth_key:
                args.v3_auth_proto = 'MD5'

        else:
            if not args.v3_auth_key:
                sys.stderr.write('ERROR: --v3-auth-key is missing\r\n')
                parser.print_usage(sys.stderr)
                return 1

        if PRIV_PROTOCOLS[args.v3_priv_proto] == config.usmNoPrivProtocol:
            if args.v3_priv_key:
                args.v3_priv_proto = 'DES'

        else:
            if not args.v3_priv_key:
                sys.stderr.write('ERROR: --v3-priv-key is missing\r\n')
                parser.print_usage(sys.stderr)
                return 1

    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 error.SnmpsimError as exc:
        sys.stderr.write('%s\r\n' % exc)
        parser.print_usage(sys.stderr)
        return 1

    if args.use_getbulk and args.protocol_version == '1':
        log.info('will be using GETNEXT with SNMPv1!')
        args.use_getbulk = False

    # Load variation module

    if args.variation_module:

        for variation_modules_dir in (
                args.variation_modules_dir or confdir.variation):
            log.info(
                'Scanning "%s" directory for variation '
                'modules...' % variation_modules_dir)

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

            mod = os.path.join(variation_modules_dir, args.variation_module + '.py')
            if not os.path.exists(mod):
                log.info('Variation module "%s" not found' % mod)
                continue

            ctx = {'path': mod, 'moduleContext': {}}

            try:
                with open(mod) as fl:
                    exec (compile(fl.read(), mod, 'exec'), ctx)

            except Exception as exc:
                log.error('Variation module "%s" execution failure: '
                          '%s' % (mod, exc))
                return 1

            variation_module = ctx
            log.info('Variation module "%s" loaded' % args.variation_module)
            break

        else:
            log.error('variation module "%s" not found' % args.variation_module)
            return 1

    # SNMP configuration

    snmp_engine = engine.SnmpEngine()

    if args.protocol_version == '3':

        if args.v3_priv_key is None and args.v3_auth_key is None:
            secLevel = 'noAuthNoPriv'

        elif args.v3_priv_key is None:
            secLevel = 'authNoPriv'

        else:
            secLevel = 'authPriv'

        config.addV3User(
            snmp_engine, args.v3_user,
            AUTH_PROTOCOLS[args.v3_auth_proto], args.v3_auth_key,
            PRIV_PROTOCOLS[args.v3_priv_proto], args.v3_priv_key)

        log.info(
            'SNMP version 3, Context EngineID: %s Context name: %s, SecurityName: %s, '
            'SecurityLevel: %s, Authentication key/protocol: %s/%s, Encryption '
            '(privacy) key/protocol: '
            '%s/%s' % (
                args.v3_context_engine_id and args.v3_context_engine_id.prettyPrint() or '<default>',
                args.v3_context_name and args.v3_context_name.prettyPrint() or '<default>', args.v3_user,
                secLevel, args.v3_auth_key is None and '<NONE>' or args.v3_auth_key,
                args.v3_auth_proto,
                args.v3_priv_key is None and '<NONE>' or args.v3_priv_key, args.v3_priv_proto))

    else:

        args.v3_user = '******'
        secLevel = 'noAuthNoPriv'

        config.addV1System(snmp_engine, args.v3_user, args.community)

        log.info(
            'SNMP version %s, Community name: '
            '%s' % (args.protocol_version, args.community))

    config.addTargetParams(
        snmp_engine, 'pms', args.v3_user, secLevel, VERSION_MAP[args.protocol_version])

    if args.agent_udpv6_endpoint:
        config.addSocketTransport(
            snmp_engine, udp6.domainName,
            udp6.Udp6SocketTransport().openClientMode())

        config.addTargetAddr(
            snmp_engine, 'tgt', udp6.domainName, args.agent_udpv6_endpoint, 'pms',
            args.timeout * 100, args.retries)

        log.info('Querying UDP/IPv6 agent at [%s]:%s' % args.agent_udpv6_endpoint)

    elif args.agent_udpv4_endpoint:
        config.addSocketTransport(
            snmp_engine, udp.domainName,
            udp.UdpSocketTransport().openClientMode())

        config.addTargetAddr(
            snmp_engine, 'tgt', udp.domainName, args.agent_udpv4_endpoint, 'pms',
            args.timeout * 100, args.retries)

        log.info('Querying UDP/IPv4 agent at %s:%s' % args.agent_udpv4_endpoint)

    log.info('Agent response timeout: %d secs, retries: '
             '%s' % (args.timeout, args.retries))

    if (isinstance(args.start_object, ObjectIdentity) or
            isinstance(args.stop_object, ObjectIdentity)):

        compiler.addMibCompiler(
            snmp_engine.getMibBuilder(), sources=args.mib_sources)

        mib_view_controller = view.MibViewController(
            snmp_engine.getMibBuilder())

        try:
            if isinstance(args.start_object, ObjectIdentity):
                args.start_object.resolveWithMib(mib_view_controller)

            if isinstance(args.stop_object, ObjectIdentity):
                args.stop_object.resolveWithMib(mib_view_controller)

        except PySnmpError as exc:
            sys.stderr.write('ERROR: %s\r\n' % exc)
            return 1

    # Variation module initialization

    if variation_module:
        log.info('Initializing variation module...')

        for x in ('init', 'record', 'shutdown'):
            if x not in variation_module:
                log.error('missing "%s" handler at variation module '
                          '"%s"' % (x, args.variation_module))
                return 1

        try:
            handler = variation_module['init']

            handler(snmpEngine=snmp_engine, options=args.variation_module_options,
                    mode='recording', startOID=args.start_object,
                    stopOID=args.stop_object)

        except Exception as exc:
            log.error(
                'Variation module "%s" initialization FAILED: '
                '%s' % (args.variation_module, exc))

        else:
            log.info(
                'Variation module "%s" initialization OK' % args.variation_module)

    data_file_handler = variation.RECORD_TYPES[args.destination_record_type]


    # SNMP worker

    def cbFun(snmp_engine, send_request_handle, error_indication,
              error_status, error_index, var_bind_table, cb_ctx):

        if error_indication and not cb_ctx['retries']:
            cb_ctx['errors'] += 1
            log.error('SNMP Engine error: %s' % error_indication)
            return

        # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
        # so we ignore noSuchName error here
        if error_status and error_status != 2 or error_indication:
            log.error(
                'Remote SNMP error %s' % (
                        error_indication or error_status.prettyPrint()))

            if cb_ctx['retries']:
                try:
                    next_oid = var_bind_table[-1][0][0]

                except IndexError:
                    next_oid = cb_ctx['lastOID']

                else:
                    log.error('Failed OID: %s' % next_oid)

                # fuzzy logic of walking a broken OID
                if len(next_oid) < 4:
                    pass

                elif (args.continue_on_errors - cb_ctx['retries']) * 10 / args.continue_on_errors > 5:
                    next_oid = next_oid[:-2] + (next_oid[-2] + 1,)

                elif next_oid[-1]:
                    next_oid = next_oid[:-1] + (next_oid[-1] + 1,)

                else:
                    next_oid = next_oid[:-2] + (next_oid[-2] + 1, 0)

                cb_ctx['retries'] -= 1
                cb_ctx['lastOID'] = next_oid

                log.info(
                    'Retrying with OID %s (%s retries left)'
                    '...' % (next_oid, cb_ctx['retries']))

                # initiate another SNMP walk iteration
                if args.use_getbulk:
                    cmd_gen.sendVarBinds(
                        snmp_engine,
                        'tgt',
                        args.v3_context_engine_id, args.v3_context_name,
                        0, args.getbulk_repetitions,
                        [(next_oid, None)],
                        cbFun, cb_ctx)

                else:
                    cmd_gen.sendVarBinds(
                        snmp_engine,
                        'tgt',
                        args.v3_context_engine_id, args.v3_context_name,
                        [(next_oid, None)],
                        cbFun, cb_ctx)

            cb_ctx['errors'] += 1

            return

        if args.continue_on_errors != cb_ctx['retries']:
            cb_ctx['retries'] += 1

        if var_bind_table and var_bind_table[-1] and var_bind_table[-1][0]:
            cb_ctx['lastOID'] = var_bind_table[-1][0][0]

        stop_flag = False

        # Walk var-binds
        for var_bind_row in var_bind_table:
            for oid, value in var_bind_row:

                # EOM
                if args.stop_object and oid >= args.stop_object:
                    stop_flag = True  # stop on out of range condition

                elif (value is None or
                          value.tagSet in (rfc1905.NoSuchObject.tagSet,
                                           rfc1905.NoSuchInstance.tagSet,
                                           rfc1905.EndOfMibView.tagSet)):
                    stop_flag = True

                # remove value enumeration
                if value.tagSet == rfc1902.Integer32.tagSet:
                    value = rfc1902.Integer32(value)

                if value.tagSet == rfc1902.Unsigned32.tagSet:
                    value = rfc1902.Unsigned32(value)

                if value.tagSet == rfc1902.Bits.tagSet:
                    value = rfc1902.OctetString(value)

                # Build .snmprec record

                context = {
                    'origOid': oid,
                    'origValue': value,
                    'count': cb_ctx['count'],
                    'total': cb_ctx['total'],
                    'iteration': cb_ctx['iteration'],
                    'reqTime': cb_ctx['reqTime'],
                    'args.start_object': args.start_object,
                    'stopOID': args.stop_object,
                    'stopFlag': stop_flag,
                    'variationModule': variation_module
                }

                try:
                    line = data_file_handler.format(oid, value, **context)

                except error.MoreDataNotification as exc:
                    cb_ctx['count'] = 0
                    cb_ctx['iteration'] += 1

                    more_data_notification = exc

                    if 'period' in more_data_notification:
                        log.info(
                            '%s OIDs dumped, waiting %.2f sec(s)'
                            '...' % (cb_ctx['total'],
                                     more_data_notification['period']))

                        time.sleep(more_data_notification['period'])

                    # initiate another SNMP walk iteration
                    if args.use_getbulk:
                        cmd_gen.sendVarBinds(
                            snmp_engine,
                            'tgt',
                            args.v3_context_engine_id, args.v3_context_name,
                            0, args.getbulk_repetitions,
                            [(args.start_object, None)],
                            cbFun, cb_ctx)

                    else:
                        cmd_gen.sendVarBinds(
                            snmp_engine,
                            'tgt',
                            args.v3_context_engine_id, args.v3_context_name,
                            [(args.start_object, None)],
                            cbFun, cb_ctx)

                    stop_flag = True  # stop current iteration

                except error.NoDataNotification:
                    pass

                except error.SnmpsimError as exc:
                    log.error(exc)
                    continue

                else:
                    args.output_file.write(line)

                    cb_ctx['count'] += 1
                    cb_ctx['total'] += 1

                    if cb_ctx['count'] % 100 == 0:
                        log.info('OIDs dumped: %s/%s' % (
                            cb_ctx['iteration'], cb_ctx['count']))

        # Next request time
        cb_ctx['reqTime'] = time.time()

        # Continue walking
        return not stop_flag

    cb_ctx = {
        'total': 0,
        'count': 0,
        'errors': 0,
        'iteration': 0,
        'reqTime': time.time(),
        'retries': args.continue_on_errors,
        'lastOID': args.start_object
    }

    if args.use_getbulk:
        cmd_gen = cmdgen.BulkCommandGenerator()

        cmd_gen.sendVarBinds(
            snmp_engine,
            'tgt',
            args.v3_context_engine_id, args.v3_context_name,
            0, args.getbulk_repetitions,
            [(args.start_object, rfc1902.Null(''))],
            cbFun, cb_ctx)

    else:
        cmd_gen = cmdgen.NextCommandGenerator()

        cmd_gen.sendVarBinds(
            snmp_engine,
            'tgt',
            args.v3_context_engine_id, args.v3_context_name,
            [(args.start_object, rfc1902.Null(''))],
            cbFun, cb_ctx)

    log.info(
        'Sending initial %s request for %s (stop at %s)'
        '....' % (args.use_getbulk and 'GETBULK' or 'GETNEXT',
                  args.start_object, args.stop_object or '<end-of-mib>'))

    started = time.time()

    try:
        snmp_engine.transportDispatcher.runDispatcher()

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

    finally:
        if variation_module:
            log.info('Shutting down variation module '
                     '%s...' % args.variation_module)

            try:
                handler = variation_module['shutdown']

                handler(snmpEngine=snmp_engine,
                        options=args.variation_module_options,
                        mode='recording')

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

            else:
                log.info(
                    'Variation module %s shutdown OK' % args.variation_module)

        snmp_engine.transportDispatcher.closeDispatcher()

        started = time.time() - started

        cb_ctx['total'] += cb_ctx['count']

        log.info(
            'OIDs dumped: %s, elapsed: %.2f sec, rate: %.2f OIDs/sec, errors: '
            '%d' % (cb_ctx['total'], started,
                    started and cb_ctx['count'] // started or 0,
                    cb_ctx['errors']))

        args.output_file.flush()
        args.output_file.close()

        return cb_ctx.get('errors', 0) and 1 or 0
Exemple #20
0
    def _write(self, keys, values, IP=None):
        '''Write keys and values to PDU.
        keys and values are lists of the same length. Example:
        keys = ['1.3.6.1.4.1.318.1.1.4.5.2.1.3.1',]
        values = [1,]
        '''
        if len(keys) != len(values):
            print 'Error: the keys and values are not matched.'
            exit()
        if IP == None:
            IP = self.ip

        # Protocol version to use
        pMod = api.protoModules[api.protoVersion1]
        # Build PDU
        reqPDU = pMod.SetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)
        pMod.apiPDU.setVarBinds(reqPDU, zip(keys, map(pMod.Integer, values)))
        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        startedAt = time()

        def cbTimerFun(timeNow):
            if timeNow - startedAt > 3:
                raise Exception('Request timed out')

        def cbRecvFun(transportDispatcher,
                      transportDomain,
                      transportAddress,
                      wholeMsg,
                      reqPDU=reqPDU):
            while wholeMsg:
                rspMsg, wholeMsg = decoder.decode(wholeMsg,
                                                  asn1Spec=pMod.Message())
                rspPDU = pMod.apiMessage.getPDU(rspMsg)
                # Match response to request
                if pMod.apiPDU.getRequestID(
                        reqPDU) == pMod.apiPDU.getRequestID(rspPDU):
                    # Check for SNMP errors reported
                    errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
                    if errorStatus:
                        print(errorStatus.prettyPrint())
                    else:
                        for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
                            #print '-----OK-----'
                            pass

                    transportDispatcher.jobFinished(1)
            return wholeMsg

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(cbRecvFun)
        transportDispatcher.registerTimerCbFun(cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openClientMode())

        # Pass message to dispatcher
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName,
                                        (IP, 161))
        transportDispatcher.jobStarted(1)
        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
Exemple #21
0
    def _read(self, keys, IP=None):
        '''read results for keys.
        keys is a list.
        '''
        if IP == None:
            IP = self.ip
        values = []

        pMod = api.protoModules[api.protoVersion1]
        # pMod = api.protoModules[api.protoVersion2c]
        # Build PDU
        reqPDU = pMod.GetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)
        ###

        pMod.apiPDU.setVarBinds(reqPDU, zip(keys, [pMod.Null('')] * len(keys)))

        # Build message
        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        startedAt = time()

        def cbTimerFun(timeNow):
            if timeNow - startedAt > 3:
                raise Exception('Request timed out')

        def cbRecvFun(transportDispatcher,
                      transportDomain,
                      transportAddress,
                      wholeMsg,
                      reqPDU=reqPDU):
            while wholeMsg:
                rspMsg, wholeMsg = decoder.decode(wholeMsg,
                                                  asn1Spec=pMod.Message())
                rspPDU = pMod.apiMessage.getPDU(rspMsg)
                # Match response to request

                if pMod.apiPDU.getRequestID(
                        reqPDU) == pMod.apiPDU.getRequestID(rspPDU):
                    # Check for SNMP errors reported
                    errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
                    if errorStatus:
                        print(errorStatus.prettyPrint())
                    else:
                        for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
                            values.append(val.prettyPrint())

                    transportDispatcher.jobFinished(1)
            return wholeMsg

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(cbRecvFun)
        transportDispatcher.registerTimerCbFun(cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openClientMode())
        # Pass message to dispatcher
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName,
                                        (IP, 161))
        transportDispatcher.jobStarted(1)
        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
        return values
Exemple #22
0
    def action(self, outlet, action, IP=None):
        '''Set parameter for PDU.'''
        if IP == None:
            IP = self.ip
        # Protocol version to use
        pMod = api.protoModules[api.protoVersion1]
        # Build PDU
        reqPDU = pMod.SetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)
        outlet = str(outlet)
        pMod.apiPDU.setVarBinds(reqPDU,
                                ((self.command['outlet_header'] + outlet,
                                  pMod.Integer(self.action_dict[action])), ))

        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        startedAt = time()

        def cbTimerFun(timeNow):
            if timeNow - startedAt > 2:
                raise Exception("Request timed out")

        # noinspection PyUnusedLocal,PyUnusedLocal
        def cbRecvFun(transportDispatcher,
                      transportDomain,
                      transportAddress,
                      wholeMsg,
                      reqPDU=reqPDU):
            while wholeMsg:
                rspMsg, wholeMsg = decoder.decode(wholeMsg,
                                                  asn1Spec=pMod.Message())
                rspPDU = pMod.apiMessage.getPDU(rspMsg)
                # Match response to request
                if pMod.apiPDU.getRequestID(
                        reqPDU) == pMod.apiPDU.getRequestID(rspPDU):
                    # Check for SNMP errors reported
                    errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
                    if errorStatus:
                        print(errorStatus.prettyPrint())
                    else:
                        for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
                            print '-----OK-----'
                            #print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
            transportDispatcher.jobFinished(1)
            return wholeMsg

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(cbRecvFun)
        transportDispatcher.registerTimerCbFun(cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openClientMode())

        # Pass message to dispatcher
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName,
                                        (IP, 161))
        transportDispatcher.jobStarted(1)
        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
Exemple #23
0
def SnmpwalkAsync(target_IP=None,
                  oid=None,
                  community='public',
                  walk_timeout=10,
                  mode='ipv4'):
    """Script to run in the remote device for snmp mib walk.

       This script can be copied to the remote device eg:wan
       and can be executed directly using python for snmp mib walk
       The walk can done for both ipv6 and ipv4

    :param target_IP: device IP for mib query
    :type target_IP: string
    :param oid: mib query OID
    :type oid: string
    :param community: community string for mib query, defaults to public
    :type community: string, optional
    :param walk_timeout: snmp walk timeout, defaults to 10
    :type walk_timeout: integer, optional
    :param mode: mib query mode, defaults to ipv4
    :type mode: string, optional
    :return: mib query output
    :rtype: string
    """
    # SNMP table header
    headVars = [v2c.ObjectIdentifier((oid))]

    # Build PDU
    reqPDU = v2c.GetBulkRequestPDU()
    v2c.apiBulkPDU.setDefaults(reqPDU)
    v2c.apiBulkPDU.setNonRepeaters(reqPDU, 0)
    v2c.apiBulkPDU.setMaxRepetitions(reqPDU, 25)
    v2c.apiBulkPDU.setVarBinds(reqPDU, [(x, v2c.null) for x in headVars])

    # Build message
    reqMsg = v2c.Message()
    v2c.apiMessage.setDefaults(reqMsg)
    v2c.apiMessage.setCommunity(reqMsg, community)
    v2c.apiMessage.setPDU(reqMsg, reqPDU)

    startedAt = time.time()
    output_list = []

    def cbTimerFun(timeNow):
        # Duration
        if timeNow - startedAt > walk_timeout:
            if walk_timeout != 0:
                raise Exception("Request timed out")
            else:
                if timeNow - startedAt > 30:
                    transportDispatcher.jobFinished(1)

    # noinspection PyUnusedLocal
    def cbRecvFun(transportDispatcher,
                  transportDomain,
                  transportAddress,
                  wholeMsg,
                  reqPDU=reqPDU,
                  headVars=headVars):
        while wholeMsg:
            rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message())
            rspPDU = v2c.apiMessage.getPDU(rspMsg)

            # Match response to request
            if v2c.apiBulkPDU.getRequestID(
                    reqPDU) == v2c.apiBulkPDU.getRequestID(rspPDU):
                # Format var-binds table
                varBindTable = v2c.apiBulkPDU.getVarBindTable(reqPDU, rspPDU)

                # Check for SNMP errors reported
                errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU)
                if errorStatus and errorStatus != 2:
                    errorIndex = v2c.apiBulkPDU.getErrorIndex(rspPDU)
                    print('%s at %s' %
                          (errorStatus.prettyPrint(), errorIndex
                           and varBindTable[int(errorIndex) - 1] or '?'))
                    transportDispatcher.jobFinished(1)
                    break

                # Report SNMP table
                for tableRow in varBindTable:
                    for name, val in tableRow:
                        # print mib data
                        print('from: %s, %s = %s' %
                              (transportAddress, name.prettyPrint(),
                               val.prettyPrint()))
                        output_list.append(
                            'from: %s, %s = %s\n' %
                            (transportAddress, name.prettyPrint(),
                             val.prettyPrint()))

                # Stop on EOM
                for oid, val in varBindTable[-1]:
                    if not isinstance(val, v2c.Null):
                        break
                    else:
                        transportDispatcher.jobFinished(1)

                # Generate request for next row
                v2c.apiBulkPDU.setVarBinds(reqPDU,
                                           [(x, v2c.null)
                                            for x, y in varBindTable[-1]])
                v2c.apiBulkPDU.setRequestID(reqPDU, v2c.getNextRequestID())
                transportDispatcher.sendMessage(encoder.encode(reqMsg),
                                                transportDomain,
                                                transportAddress)
        return wholeMsg

    transportDispatcher = AsyncoreDispatcher()
    transportDispatcher.registerRecvCbFun(cbRecvFun)
    transportDispatcher.registerTimerCbFun(cbTimerFun)
    if mode == 'ipv4':
        transportDispatcher.registerTransport(
            udp.domainName,
            udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName,
                                        (target_IP, 161))
    else:
        transportDispatcher.registerTransport(
            udp6.domainName,
            udp6.Udp6SocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg),
                                        udp6.domainName, (target_IP, 161))
    transportDispatcher.jobStarted(1)
    # Dispatcher will finish as job#1 counter reaches zero
    transportDispatcher.runDispatcher()
    transportDispatcher.closeDispatcher()

    if output_list != []:
        return output_list
    else:
        return
                varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBinds(reqPDU)
            print('Var-binds:')
            for oid, val in varBinds:
                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
    return wholeMsg


transportDispatcher = AsyncoreDispatcher()

transportDispatcher.registerRecvCbFun(cbFun)

# UDP/IPv4
transportDispatcher.registerTransport(
    udp.domainName, udp.UdpSocketTransport().openServerMode(('192.168.169.169', 162))
)

# UDP/IPv6
transportDispatcher.registerTransport(
    udp6.domainName, udp6.Udp6SocketTransport().openServerMode(('::1', 162))
)

## Local domain socket
# transportDispatcher.registerTransport(
#    unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-manager')
# )

transportDispatcher.jobStarted(1)

try:
Exemple #25
0
                    "TRAP\tERROR | Failed to resolve symbol ({}={})".format(
                        key, value))
                continue
            key, value = parsed.prettyPrint().split(" = ")
            logger.info("TRAP\t{} | {}".format(key, value))

            if key == "PowerNet-MIB::mtrapargsString.0":
                message = value
                for contact in contacts['contacts']:
                    phoneNumber = contact['phoneNumber']
                    _redis.publish(
                        'sms',
                        json.dumps(
                            dict(phoneNumber=phoneNumber, message=message)))

    return msg


dispatcher = AsyncoreDispatcher()
dispatcher.registerRecvCbFun(snmpRecvCallback)
dispatcher.registerTransport(
    udp.domainName,
    udp.UdpSocketTransport().openServerMode((TRAP_IP_ADDRESS, TRAP_PORT)))
dispatcher.jobStarted(1)
print("Starting...")
try:
    dispatcher.runDispatcher()
except:
    dispatcher.closeDispatcher()
    raise
            # Incluir el contenido de las varBinds en el correo electronico





    return wholeMsg


transportDispatcher = AsyncoreDispatcher()

transportDispatcher.registerRecvCbFun(cbFun)

# UDP/IPv4
transportDispatcher.registerTransport(
    udp.domainName, udp.UdpSocketTransport().openServerMode(('0.0.0.0', 162))
)

# UDP/IPv6
transportDispatcher.registerTransport(
    udp6.domainName, udp6.Udp6SocketTransport().openServerMode(('::1', 162))
)


transportDispatcher.jobStarted(1)

try:
    # Dispatcher will never finish as job#1 never reaches zero
    transportDispatcher.runDispatcher()
except:
    transportDispatcher.closeDispatcher()
Exemple #27
0
# Traps have quite different semantics across proto versions
if pMod == api.PROTOCOL_MODULES[api.SNMP_VERSION_1]:
    pMod.apiTrapPDU.setEnterprise(trapPDU, (1, 3, 6, 1, 1, 2, 3, 4, 1))
    pMod.apiTrapPDU.setGenericTrap(trapPDU, 'coldStart')

# Build message
trapMsg = pMod.Message()
pMod.apiMessage.setDefaults(trapMsg)
pMod.apiMessage.setCommunity(trapMsg, 'public')
pMod.apiMessage.setPDU(trapMsg, trapPDU)

transportDispatcher = AsyncoreDispatcher()

# UDP/IPv4
transportDispatcher.registerTransport(
    udp.DOMAIN_NAME, udp.UdpSocketTransport().openClientMode()
)

transportDispatcher.sendMessage(
    encoder.encode(trapMsg), udp.DOMAIN_NAME, ('demo.snmplabs.com', 162)
)

# UDP/IPv6
transportDispatcher.registerTransport(
    udp6.DOMAIN_NAME, udp6.Udp6SocketTransport().openClientMode()
)

transportDispatcher.sendMessage(
    encoder.encode(trapMsg), udp6.DOMAIN_NAME, ('::1', 162)
)
Exemple #28
0
                print('Specific Trap: %s' %
                      (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()))
                print('Uptime: %s' %
                      (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()))
                varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
            else:
                varBinds = pMod.apiPDU.getVarBindList(reqPDU)
            print('Var-binds:')
            for oid, val in varBinds:
                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
    return wholeMsg


transportDispatcher = AsyncoreDispatcher()

transportDispatcher.registerRecvCbFun(cbFun)

# UDP/IPv4
transportDispatcher.registerTransport(
    udp.domainName,
    udp.UdpSocketTransport().openServerMode((IPADDR, PORT)))

transportDispatcher.jobStarted(1)

try:
    # Dispatcher will never finish as job#1 never reaches zero
    transportDispatcher.runDispatcher()
except:
    transportDispatcher.closeDispatcher()
    raise
Exemple #29
0
#

# user: usr-sha-aes, auth: SHA, priv AES
config.addV3User(snmpEngine, 'usr-sha-aes', config.USM_AUTH_HMAC96_SHA,
                 'authkey1', config.USM_PRIV_CFB128_AES, 'privkey1')

config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv')

#
# Setup transport endpoint and bind it with security settings yielding
# a target name
#

# UDP/IPv4
config.addTransport(snmpEngine, udp.DOMAIN_NAME,
                    udp.UdpSocketTransport().openClientMode())

config.addTargetAddr(snmpEngine, 'my-router', udp.DOMAIN_NAME,
                     ('104.236.166.95', 161), 'my-creds')


# Error/response receiver
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus,
          errorIndex, varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)

    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
Exemple #30
0
            from wework import WeApp
            app = WeApp('container')
            app.send_room_msg(wework_msg)

    return wholeMsg


transportDispatcher = AsyncoreDispatcher()

transportDispatcher.registerRecvCbFun(cbFun)

# UDP/IPv4
transportDispatcher.registerTransport(
    udp.domainName,
    udp.UdpSocketTransport().openServerMode((NMS_IP, 162)))

# UDP/IPv6
transportDispatcher.registerTransport(
    udp6.domainName,
    udp6.Udp6SocketTransport().openServerMode(('::1', 162)))

## Local domain socket
# transportDispatcher.registerTransport(
#    unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-manager')
# )

transportDispatcher.jobStarted(1)

try:
    # Dispatcher will never finish as job#1 never reaches zero