Beispiel #1
0
    def __init__(self, data, timeout_func=None, receive_func=None, error_func=None):
        self.__dict__.update(data)

        self.timeout_func = timeout_func
        self.receive_func = receive_func
        self.error_func = error_func

        self.pMod = pMod = api.protoModules[api.protoVersion2c]

        self.reqPDU = reqPDU = pMod.SetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)

        pMod.apiPDU.setVarBinds(reqPDU,
                                map(lambda a: (a[0], pMod.OctetString(str(a[2]))) if a[1] == 'str'
                                    else (a[0], pMod.Integer(int(a[2]))), self.oid_keys_enc_val))

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

        self.startedAt = time()

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

        # UDP/IPv4
        transportDispatcher.registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName, (self.network_address, self.port))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
Beispiel #2
0
    def __init__(self, data, timeout_func=None, receive_func=None, error_func=None):
        self.__dict__.update(data)

        self.timeout_func = timeout_func
        self.receive_func = receive_func
        self.error_func = error_func

        headVars = [v2c.ObjectIdentifier(oid) for oid in
                    map(lambda oid: (int(i) for i in oid.split('.')), self.oid_keys)]

        self.reqPDU = reqPDU = v2c.GetBulkRequestPDU()
        v2c.apiBulkPDU.setDefaults(reqPDU)
        v2c.apiBulkPDU.setNonRepeaters(reqPDU, self.non_repeaters)
        v2c.apiBulkPDU.setMaxRepetitions(reqPDU, self.max_repetitions)
        v2c.apiBulkPDU.setVarBinds(reqPDU, [(x, v2c.null) for x in headVars])

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

        self.startedAt = time()

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

        transportDispatcher.registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName, (self.network_address, self.port))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
Beispiel #3
0
    def __init__(self, data, timeout_func=None, receive_func=None, error_func=None):
        self.__dict__.update(data)

        self.timeout_func = timeout_func
        self.receive_func = receive_func
        self.error_func = error_func

        self.pMod = pMod = api.protoModules[api.protoVersion2c]
        self.reqPDU = reqPDU = pMod.GetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)

        pMod.apiPDU.setVarBinds(reqPDU, ((oid, pMod.Null('')) for oid in self.oid_keys))

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

        self.startedAt = time()

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

        # UDP/IPv4
        transportDispatcher.registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName, (self.network_address, self.port))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
Beispiel #4
0
        # 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()))
            transportDispatcher.jobFinished(1)
    return wholeMsg

transportDispatcher = AsyncoreDispatcher()

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

# Initialize UDP/IPv4 transport
udpSocketTransport = udp.UdpSocketTransport().openClientMode()

# Use sendmsg()/recvmsg() for socket communication (required for
# IP source spoofing functionality)
udpSocketTransport.enablePktInfo()

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

transportDispatcher.registerTransport(udp.domainName, udpSocketTransport)

# Pass message to dispatcher
transportDispatcher.sendMessage(
Beispiel #5
0
                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()))
            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,
                                ('192.168.1.88', 161))
transportDispatcher.jobStarted(1)

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

transportDispatcher.closeDispatcher()
Beispiel #6
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
Beispiel #7
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("")
Beispiel #8
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()
Beispiel #9
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
Beispiel #10
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()
Beispiel #11
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()
Beispiel #12
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()