Ejemplo n.º 1
0
  def getDescHost(self):
    self.txtDisplay.clear()

    self.txtDisplay.append("<span style='color:#00FFFF;font-weight:bold'>Informação do Host</span>")

    alvoTexto = self.inputIPAlvo.text()
    alvo = alvoTexto[:15]
    cmdGen = cmdgen.CommandGenerator()

    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
      cmdgen.CommunityData('public', mpModel=0),
      cmdgen.UdpTransportTarget((alvo, 161)),
      cmdgen.MibVariable('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0'),
      cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0)
    )

    # Check for errors and print out results
    if errorIndication:
      self.txtDisplay.append(str(errorIndication))

    else:
      if errorStatus:

        self.txtDisplay.append(
          '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1] or '?'))


      else:
        for nome, val in varBinds:
          self.txtDisplay.append('%s = %s' % (nome.prettyPrint(), val.prettyPrint()))
Ejemplo n.º 2
0
    def _get_mib_bulkwalk(self, community, prefix, table, path=None):
        '''
        % snmpbulkwalk -v2c -c public myhost123 TCP-MIB::tcpConnTable
        '''

        mib = None
        if path:
            mib = cmdgen.MibVariable(prefix, table).addMibSource(path)
        else:
            mib = cmdgen.MibVariable(prefix, table)
        real_fun = getattr(self.generator, 'bulkCmd')  # SNMPBULKWALK
        res = errorIndication, errorStatus, errorIndex, varBinds = real_fun(self.comm_data, self.transport, 0, 50, mib,
                                                                            max_rows=100,
                                                                            ignore_non_increasing_oid=True)

        if errorIndication is not None or errorStatus is True:
            msg = 'Error: %s %s %s %s' % res
            raise SnmpError(msg)
        else:
            res = {}
            for items in varBinds:
                oid = str(items[0][0])
                val = items[0][1]
                if isinstance(val, Counter64) or isinstance(val, Counter32) or isinstance(val, Integer):
                    res[oid] = int(val)
                else:
                    res[oid] = str(val)
            return res
 def mibvariable(self, mib_name, mib_index, mib_value=''):
     """
     Creates MIB Object
     Arguments:
         1.(string) mib_name="IP-MIB"
         2.(string) mib_index="ipAdEntAddr"
         3.(string) mib_value="127.0.0.1"
     Return: MIB Object
     """
     if mib_value:
         return cmdgen.MibVariable(mib_name, mib_index, mib_value)
     else:
         return cmdgen.MibVariable(mib_name, mib_index)
Ejemplo n.º 4
0
def get_all_interface(host, community):
    """
    获取某主机上的所有端口
    """
    all_interfaces = []
    gen = cmdgen.CommandGenerator()

    if_descr_oid = cmdgen.MibVariable('IF-MIB', 'ifDescr')

    # 获取所有的端口描述
    error_indication, error_status, error_index, var_binds = gen.nextCmd(
        cmdgen.CommunityData(community),
        cmdgen.UdpTransportTarget((host, 161)),
        if_descr_oid,
    )

    interface = None
    if not error_indication:
        for var in var_binds:
            for i in var:
                temp = {}
                key = i[0].asTuple()
                value = i[1]
                temp['index'] = key[-1]
                temp['name'] = str(value)
                all_interfaces.append(temp)

    if_status_oid = cmdgen.MibVariable('IF-MIB', 'ifOperStatus')

    # 获取所有的端口状态
    error_indication, error_status, error_index, var_binds = gen.nextCmd(
        cmdgen.CommunityData(community),
        cmdgen.UdpTransportTarget((host, 161)),
        if_status_oid,
    )

    all_interfaces_status = {}
    if not error_indication:
        for var in var_binds:
            for i in var:
                key = i[0].asTuple()
                value = i[1]
                all_interfaces_status[key[-1]] = int(value)

    for interface in all_interfaces:
        if interface['index'] in all_interfaces_status:
            interface['status'] = all_interfaces_status[interface['index']]

    return all_interfaces
Ejemplo n.º 5
0
    def test_snmp_get(self):
        self.simulator.add_walkfile(WALK_FILE)

        def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
                  varBinds, cbCtx):
            if errorIndication or errorStatus:
                raise Exception('SNMP error!')

            oid, val = varBinds[0]
            assert oid.prettyPrint() == '1.3.6.1.2.1.1.1.0'
            assert val.prettyPrint().startswith('Cisco')

        cmdGen = cmdgen.AsynCommandGenerator()
        cmdGen.getCmd(cmdgen.CommunityData('public'),
                      cmdgen.UdpTransportTarget(('127.0.0.1', 1161)),
                      (cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), ),
                      (cbFun, None))
        simulator_snmpEngine = self.simulator.snmp_agent.snmpEngine
        while cmdGen.snmpEngine.transportDispatcher.jobsArePending(
        ) or cmdGen.snmpEngine.transportDispatcher.transportsAreWorking():
            asyncore.poll(0.001,
                          cmdGen.snmpEngine.transportDispatcher.getSocketMap())
            cmdGen.snmpEngine.transportDispatcher.handleTimerTick(time.time())

            asyncore.poll(
                0.001, simulator_snmpEngine.transportDispatcher.getSocketMap())
            simulator_snmpEngine.transportDispatcher.handleTimerTick(
                time.time())
Ejemplo n.º 6
0
    def __init__(self, config):
        """Initialize the scanner."""
        from pysnmp.entity.rfc3413.oneliner import cmdgen
        from pysnmp.entity import config as cfg
        self.snmp = cmdgen.CommandGenerator()

        self.host = cmdgen.UdpTransportTarget((config[CONF_HOST], 161))
        if CONF_AUTHKEY not in config or CONF_PRIVKEY not in config:
            self.auth = cmdgen.CommunityData(config[CONF_COMMUNITY])
        else:
            self.auth = cmdgen.UsmUserData(
                config[CONF_COMMUNITY],
                config[CONF_AUTHKEY],
                config[CONF_PRIVKEY],
                authProtocol=cfg.usmHMACSHAAuthProtocol,
                privProtocol=cfg.usmAesCfb128Protocol)
        self.baseoid = cmdgen.MibVariable(config[CONF_BASEOID])

        self.lock = threading.Lock()

        self.last_results = []

        # Test the router is accessible
        data = self.get_snmp_data()
        self.success_init = data is not None
Ejemplo n.º 7
0
    def get(self, oid, subindex=None, timeout=3, retries=1, **kwargs):
        mibVariable = cmdgen.MibVariable(*oid)
        mibVariable.resolveWithMib(self.mibViewController)
        modName, symName, indices = mibVariable.getMibSymbol()
        oid_to_get = mibVariable.asTuple()

        if subindex:
            oid_to_get += subindex

        cmdGen = cmdgen.CommandGenerator()
        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            self.auth_data,
            self.udp_transport_target,
            oid_to_get,
            # lookupNames=True, lookupValues=True
        )
        error = self.handle_snmp_error(errorIndication, errorStatus, errorIndex, varBinds)
        if error:
            raise SnmpRuntimeError(error['msg'])
        else:
            # for oid, value in varBinds:
            #     print 'oid, value', modName, symName, indices, oid, value.prettyPrint()
            # return '1.2.3.4'
            value = varBinds[0][1]
            return mibVariable.getMibNode().syntax.clone(value).prettyPrint()
Ejemplo n.º 8
0
    def _get_pdu_ports(self):
        """
        @summary: Helper method for getting PDU ports connected to PSUs of DUT

        The PDU ports connected to DUT must have hostname of DUT configured in port name/description.
        This method depends on this configuration to find out the PDU ports connected to PSUs of specific DUT.
        """
        cmdGen = cmdgen.CommandGenerator()
        snmp_auth = cmdgen.CommunityData('public')
        errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
            snmp_auth,
            cmdgen.UdpTransportTarget((self.controller, 161)),
            cmdgen.MibVariable(self.pPORT_NAME_BASE_OID, ),
        )
        if errorIndication:
            logging.debug(
                "Failed to get ports controlling PSUs of DUT, exception: " +
                str(errorIndication))
        for varBinds in varTable:
            for oid, val in varBinds:
                current_oid = oid.prettyPrint()
                current_val = val.prettyPrint()
                if self.hostname.lower() in current_val.lower():
                    # Remove the preceding PORT_NAME_BASE_OID, remaining string is the PDU port ID
                    self.pdu_ports.append(
                        current_oid.replace(self.PORT_NAME_BASE_OID, ''))
Ejemplo n.º 9
0
    def _check(self, instance):
        '''
        Perform two series of SNMP requests, one for all that have MIB asociated
        and should be looked up and one for those specified by oids
        '''

        ip_address, tags, metrics, timeout, retries = self._load_conf(instance)

        tags += ['snmp_device:{0}'.format(ip_address)]

        table_oids = []
        raw_oids = []

        # Check the metrics completely defined
        for metric in metrics:
            if 'MIB' in metric:
                try:
                    assert "table" in metric or "symbol" in metric
                    to_query = metric.get("table", metric.get("symbol"))
                    table_oids.append(
                        cmdgen.MibVariable(metric["MIB"], to_query))
                except Exception as e:
                    self.log.warning(
                        "Can't generate MIB object for variable : %s\n"
                        "Exception: %s", metric, e)
            elif 'OID' in metric:
                raw_oids.append(metric['OID'])
            else:
                raise Exception('Unsupported metric in config file: %s' %
                                metric)
        try:
            if table_oids:
                self.log.debug("Querying device %s for %s oids", ip_address,
                               len(table_oids))
                table_results = self.check_table(instance, table_oids, True,
                                                 timeout, retries)
                self.report_table_metrics(metrics, table_results, tags)

            if raw_oids:
                self.log.debug("Querying device %s for %s oids", ip_address,
                               len(raw_oids))
                raw_results = self.check_table(instance, raw_oids, False,
                                               timeout, retries)
                self.report_raw_metrics(metrics, raw_results, tags)
        except Exception as e:
            if "service_check_error" not in instance:
                instance[
                    "service_check_error"] = "Fail to collect metrics: {0}".format(
                        e)
            self.warning(instance["service_check_error"])
            return [(self.SC_STATUS, Status.CRITICAL,
                     instance["service_check_error"])]
        finally:
            # Report service checks
            tags = ["snmp_device:%s" % ip_address]
            if "service_check_error" in instance:
                return [(self.SC_STATUS, Status.DOWN,
                         instance["service_check_error"])]

            return [(self.SC_STATUS, Status.UP, None)]
Ejemplo n.º 10
0
    def read_host_values(self, host):
        cmdGen = cmdgen.CommandGenerator()

        errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
            cmdgen.CommunityData('public'),
            cmdgen.UdpTransportTarget((host, 161)),
            cmdgen.MibVariable('IF-MIB', '').loadMibs(),
            lexicographicMode=True,
            maxRows=100,
            ignoreNonIncreasingOid=True,
            lookupNames=True,
            lookupValues=True)

        if errorIndication:
            raise SnmpError('%s: %s' % (host, errorIndication))

        if errorStatus:
            raise SnmpError(
                'SNMP Walk on %s: %s at %s' %
                (host, errorStatus.prettyPrint(),
                 errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'))

        values = {}

        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                values[name.prettyPrint()] = val.prettyPrint()

        return values
Ejemplo n.º 11
0
    def get_snmp_data(self):
        """ Fetch mac addresses from WAP via SNMP. """
        from pysnmp.entity.rfc3413.oneliner import cmdgen

        devices = []

        snmp = cmdgen.CommandGenerator()
        errindication, errstatus, errindex, restable = snmp.nextCmd(
            cmdgen.CommunityData(self.community),
            cmdgen.UdpTransportTarget((self.host, 161)),
            cmdgen.MibVariable(self.baseoid)
        )

        if errindication:
            _LOGGER.error("SNMPLIB error: %s", errindication)
            return
        if errstatus:
            _LOGGER.error('SNMP error: %s at %s', errstatus.prettyPrint(),
                          errindex and restable[-1][int(errindex)-1]
                          or '?')
            return

        for resrow in restable:
            for _, val in resrow:
                mac = binascii.hexlify(val.asOctets()).decode('utf-8')
                mac = ':'.join([mac[i:i+2] for i in range(0, len(mac), 2)])
                devices.append({'mac': mac})
        return devices
Ejemplo n.º 12
0
def import_snmp():
    if not hasattr(settings, "ARPWATCH_SNMP_SERVER"):
        raise ArpImportError("Missing ARPWATCH_SNMP_SERVER setting")
    if not hasattr(settings, "ARPWATCH_SNMP_COMMUNITY"):
        raise ArpImportError("Missing ARPWATCH_SNMP_COMMUNITY setting")
    if not hasattr(settings, "ARPWATCH_NETWORK_PREFIX"):
        raise ArpImportError("Missing ARPWATCH_NETWORK_PREFIX setting")

    # Mark the time
    runtime = timezone.now()

    # Fire off the SNMP command
    logger.debug("connecting to %s..." % settings.ARPWATCH_SNMP_SERVER)
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.nextCmd(
        cmdgen.CommunityData(settings.ARPWATCH_SNMP_COMMUNITY),
        cmdgen.UdpTransportTarget((settings.ARPWATCH_SNMP_SERVER, 161)),
        cmdgen.MibVariable('IP-MIB', 'ipNetToMediaPhysAddress'),
        lookupNames=True, lookupValues=True
    )
    if errorIndication:
        raise errorIndication

    # Extract the MAC Addresses and IP Addresses from the data
    for row in varBinds:
        print(row)
        for name, val in row:
            long_name = name.prettyPrint()
            # Search data returned for an IP address
            if settings.ARPWATCH_NETWORK_PREFIX in long_name:
                ip_index = long_name.index(settings.ARPWATCH_NETWORK_PREFIX)
                ip = long_name[ip_index:]
                mac = val.prettyPrint()
                # print(f"{mac} = {ip}")
                log_data(runtime, ip, mac)
Ejemplo n.º 13
0
 def get_pdu_controller_type(self):
     """
     @summary: Use SNMP to get the type of PDU controller host
     @param pdu_controller_host: IP address of PDU controller host
     @return: Returns type string of the specified PDU controller host
     """
     pSYSDESCR = ".1.3.6.1.2.1.1.1.0"
     SYSDESCR = "1.3.6.1.2.1.1.1.0"
     pdu = None
     cmdGen = cmdgen.CommandGenerator()
     snmp_auth = cmdgen.CommunityData(self.snmp_rocommunity)
     errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
         snmp_auth,
         cmdgen.UdpTransportTarget((self.controller, 161), timeout=5.0),
         cmdgen.MibVariable(pSYSDESCR)
         )
     if errorIndication:
         logging.info("Failed to get pdu controller type, exception: " + str(errorIndication))
     for oid, val in varBinds:
         current_oid = oid.prettyPrint()
         current_val = val.prettyPrint()
         if current_oid == SYSDESCR:
             pdu = current_val
     if pdu is None:
         self.pduType = None
         return
     if 'Sentry Switched PDU' in pdu:
         self.pduType = "SENTRY4"
     if 'Sentry Switched CDU' in pdu:
         self.pduType = "SENTRY"
     if 'APC Web/SNMP Management Card' in pdu:
         self.pduType = "APC"
     if 'Emerson' in pdu:
         self.pduType = 'Emerson'
     return
Ejemplo n.º 14
0
    def get_snmp(self, ip, job_id):
        try:
            cmdGen = cmdgen.CommandGenerator()

            errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
                cmdgen.CommunityData('public'),
                cmdgen.UdpTransportTarget(('ip', 161)),
                cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
                lookupNames=True,
                lookupValues=True)

            # Check for errors and print out results
            if errorIndication:
                Config.log.debug('SNMP Get error: %s' % errorIndication)
            else:
                if errorStatus:
                    Config.log.debug(
                        'SNMP Get error %s at %s' %
                        (errorStatus.prettyPrint(),
                         errorIndex and varBinds[int(errorIndex) - 1] or '?'))
                else:
                    for name, val in varBinds:
                        Config.log.debug(
                            '%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
                        Config.client.post(
                            '/snmp/get', {
                                "job_id": job_id,
                                "ip": ip,
                                "sysDesc": val.prettyPrint()
                            })
        except:
            Config.log.debug('SNMP get timeout')
            return None
Ejemplo n.º 15
0
    def Get(self, msg):
        """Get the power status of a device.

        Arguments:
        msg: type control_pb2.GetRequest

	Returns:
        control_pb2.GetResponse
        """
        if msg.type != control_pb2.FEAT_PWR:
            log.exception('Invalid Type: %d' % (msg.type))
        response = control_pb2.GetResponse()
        errorIndication, errorStatus, errorIndex, varBinds = self.cmdGen.getCmd(
            cmdgen.CommunityData(SNMP_APC_USER, mpModel=0),
            cmdgen.UdpTransportTarget((self.device.server, SNMP_UDP_PORT)),
            cmdgen.MibVariable(SNMP_APC_PORT_VAR + str(self.device.port))
        )
        
        if self._CheckResponseOk(response, errorIndication, errorStatus, errorIndex, varBinds):
            assert(len(varBinds) == 1)
            val = varBinds[0][1]
            for k, v in PWR_COMMANDS.iteritems():
                if val == v:
                    response.value = k
                response.result = True
        log.debug('Return %d' % response.value)
    	return response
Ejemplo n.º 16
0
 def __init__(self, oid, callback=None, value=None, **kw):
     self.oid = oid
     self.raw_oid = cmdgen.MibVariable(oid)
     self.cb_func = callback
     self.filter_ = kw.pop('filter', None)
     self.cb_data = kw
     self._value = value
Ejemplo n.º 17
0
 def set_named(self, mib, index, oid2value):
     varBinds = []
     for symbol, value in oid2value:
         mv_arg = (mib, symbol) + index
         mv = cmdgen.MibVariable(*mv_arg)
         mv.resolveWithMib(self.mibViewController)
         varBinds.append((mv, value))
     self.set(varBinds)
Ejemplo n.º 18
0
    def check(self, instance):
        '''
        Perform two series of SNMP requests, one for all that have MIB asociated
        and should be looked up and one for those specified by oids
        '''
        tags = instance.get("tags", [])
        ip_address = instance["ip_address"]
        table_oids = []
        raw_oids = []

        # Check the metrics completely defined
        for metric in instance.get('metrics', []):
            if 'MIB' in metric:
                try:
                    assert "table" in metric or "symbol" in metric
                    to_query = metric.get("table", metric.get("symbol"))
                    table_oids.append(
                        cmdgen.MibVariable(metric["MIB"], to_query))
                except Exception as e:
                    self.log.warning(
                        "Can't generate MIB object for variable : %s\n"
                        "Exception: %s", metric, e)
            elif 'OID' in metric:
                raw_oids.append(metric['OID'])
            else:
                raise Exception('Unsupported metric in config file: %s' %
                                metric)
        try:
            if table_oids:
                self.log.debug("Querying device %s for %s oids", ip_address,
                               len(table_oids))
                table_results = self.check_table(instance, table_oids, True)
                self.report_table_metrics(instance, table_results)

            if raw_oids:
                self.log.debug("Querying device %s for %s oids", ip_address,
                               len(raw_oids))
                raw_results = self.check_table(instance, raw_oids, False)
                self.report_raw_metrics(instance, raw_results)
        except Exception as e:
            if "service_check_error" not in instance:
                instance[
                    "service_check_error"] = "Fail to collect metrics: {0}".format(
                        e)
            raise
        finally:
            # Report service checks
            service_check_name = "snmp.can_check"
            tags = ["snmp_device:%s" % ip_address]
            if "service_check_error" in instance:
                self.service_check(service_check_name,
                                   AgentCheck.CRITICAL,
                                   tags=tags,
                                   message=instance["service_check_error"])
            else:
                self.service_check(service_check_name,
                                   AgentCheck.OK,
                                   tags=tags)
Ejemplo n.º 19
0
    def get_outlet_status(self, outlet=None):
        """
        @summary: Use SNMP to get status of PDU ports supplying power to PSUs of DUT

        DUT hostname must be configured in PDU port name/description. But it is hard to specify which PDU port is
        connected to the first PSU of DUT and which port is connected to the second PSU.

        Because of this, currently we just find out which PDU ports are connected to PSUs of which DUT. We cannot
        find out the exact mapping between PDU outlets and PSUs of DUT.

        To overcome this limitation, the trick is to convert the specified outlet to integer, then calculate the mode
        upon the number of PSUs on DUT. The calculated mode is used as an index to get PDU outlet ID stored in
        self.pdu_ports. But still, we cannot guarantee that outlet 0 is first PSU of DUT, and so on.

        @param outlet: Optional. If specified, only return status of PDU outlet connected to specified PSU of DUT. If
                       omitted, return status of all PDU outlets connected to PSUs of DUT.
        @return: Return status of PDU outlets connected to PSUs of DUT in a list of dictionary. Example result:
                     [{"outlet_id": 0, "outlet_on": True}, {"outlet_id": 1, "outlet_on": True}]
                 The outlet in returned result is integer starts from 0.
        """
        results = []
        if not self.pduType:
            logging.error(
                'Unable to retrieve status: PDU type is unknown: pdu_ip {} dut {}'
                .format(self.controller, self.hostname))
            return results

        cmdGen = cmdgen.CommandGenerator()
        snmp_auth = cmdgen.CommunityData(self.snmp_rocommunity)
        errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
            snmp_auth,
            cmdgen.UdpTransportTarget((self.controller, 161)),
            cmdgen.MibVariable(self.pPORT_STATUS_BASE_OID, ),
        )
        if errorIndication:
            logging.debug(
                "Failed to get ports controlling PSUs of DUT, exception: " +
                str(errorIndication))
        for varBinds in varTable:
            for oid, val in varBinds:
                current_oid = oid.prettyPrint()
                current_val = val.prettyPrint()
                for idx, port in enumerate(self.pdu_ports):
                    port_oid = self.PORT_STATUS_BASE_OID + port
                    if current_oid == port_oid:
                        status = {
                            "outlet_id":
                            idx,
                            "outlet_on":
                            True if current_val == self.STATUS_ON else False
                        }
                        results.append(status)
        if outlet is not None:
            idx = int(outlet) % len(self.pdu_ports)
            results = results[idx:idx + 1]
        logging.info("Got outlet status: %s" % str(results))
        return results
Ejemplo n.º 20
0
def main():
    for ip in IP:
        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            cmdgen.CommunityData('password'),
            cmdgen.UdpTransportTarget((ip, 161)),
            cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0),
            cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
            lookupNames=True, lookupValues=True
)

        # Check for errors and print out results
        if errorIndication:
            print(errorIndication)
        elif errorStatus:
            print(errorStatus)
        else:
            for name, val in varBinds:
                print('%s = %s\n' % (name.prettyPrint(), val.prettyPrint()))
Ejemplo n.º 21
0
    def _get_string_value(self, oid):
        cmd = cmdgen.CommandGenerator()

        error_indication, error_status, error_index, var_binds = cmd.getCmd(
            cmdgen.CommunityData('public', mpModel=0),
            cmdgen.UdpTransportTarget((self.ip, 161)), cmdgen.MibVariable(oid))

        if not error_indication and not error_status:
            result = var_binds[0][1]._value

        return result
Ejemplo n.º 22
0
    def set_objects_to_poll(self, objects_to_poll):

        self.targets = []
        self.get_targets = []
        self.walk_targets = []
        self.objects_to_poll = objects_to_poll

        for object_to_poll in self.objects_to_poll:
            target_gets_def = []
            target_walks_def = []
            get_mib_variables = []
            for field, field_property in object_to_poll.properties.iteritems():

                mibVariable = cmdgen.MibVariable(*field_property.oid)
                mibVariable.resolveWithMib(self.mibViewController)
                modName, symName, indices = mibVariable.getMibSymbol()

                if field_property.method == 'get':
                    # get_mib_variables.append(mibVariable)
                    target_gets_def.append(mibVariable)
                else:
                    object_to_poll.setattr(field, [])

                    # self.walk_targets.append((
                    #     cmdgen.CommunityData(object_to_poll.community, mpModel=0),
                    #     cmdgen.UdpTransportTarget((object_to_poll.ip, object_to_poll.port),
                    #         timeout=object_to_poll.timeout,
                    #         retries=object_to_poll.retries
                    #     ),
                    #     [mibVariable],
                    # ))
                    target_walks_def.append(mibVariable)

            self.targets.append((cmdgen.CommunityData(object_to_poll.community,
                                                      mpModel=0),
                                 cmdgen.UdpTransportTarget(
                                     (object_to_poll.ip, object_to_poll.port),
                                     timeout=object_to_poll.timeout,
                                     retries=object_to_poll.retries),
                                 target_gets_def, target_walks_def))

            # properties = object_to_poll.properties
            # mib_variables = self._get_mib_variables(properties.values())

            # logger.info("[SnmpPoller] set_objects_to_poll addr=%s", object_to_poll.ip)
            if get_mib_variables:
                self.get_targets.append((
                    cmdgen.CommunityData(object_to_poll.community, mpModel=0),
                    cmdgen.UdpTransportTarget(
                        (object_to_poll.ip, object_to_poll.port),
                        timeout=object_to_poll.timeout,
                        retries=object_to_poll.retries),
                    get_mib_variables,
                ))
Ejemplo n.º 23
0
def checksnmpservice(target):
    ''' Verifica se o Host responde a um SNMP Get e retorna verdadeiro ou falso seguido do nome do Host '''
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
        cmdgen.CommunityData(settings.DEFAULT_COMMUNITY),
        cmdgen.UdpTransportTarget((target, settings.DEFAULT_PORT)),
        cmdgen.MibVariable(settings.SNMP_VERSION, settings.DEFAULT_FIELD, 0)
    )
    if errorIndication is None:
        return True, varBinds[0][1]
    else:
        return False, ''
Ejemplo n.º 24
0
    def _get_mib(self, community, prefix, extend, mib_result='nsExtendOutputFull', path=None):
        '''Parameter: mib_result can be 'nsExtendOutputFull', 'nsExtendResult', ..
        Example:
        _get_mib("public", "NET-SNMP-EXTEND-MIB", "check_postgres_backup")
        is the same like:
        % snmpget -v2c -c public z-storage02 'NET-SNMP-EXTEND-MIB::nsExtendOutputFull."check_postgres_backup"'
        '''

        mib = None
        if path:
            mib = cmdgen.MibVariable(prefix, mib_result, extend).addMibSource(path)
        else:
            mib = cmdgen.MibVariable(prefix, mib_result, extend)
        real_fun = getattr(self.generator, 'getCmd')  # SNMPGET
        res = errorIndication, errorStatus, errorIndex, varBinds = real_fun(self.comm_data, self.transport, mib)

        if errorIndication is not None or errorStatus is True:
            msg = 'Error: %s %s %s %s' % res
            raise SnmpError(msg)
        else:
            _, val = varBinds[0]
            return val
Ejemplo n.º 25
0
    def __init__(self, name=None, domain=None, port=161):
        super(SNMPStatusSource, self).__init__(name)

        if domain is None:
            raise ValueError("domain must be specified.")

        self.domain = domain
        self.port = port
        self.commands = [
            cmdgen.CommunityData('public'),
            cmdgen.UdpTransportTarget((self.domain, self.port)),
            cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0)
        ]
Ejemplo n.º 26
0
    def _get_float_value(self, oid):
        cmd = cmdgen.CommandGenerator()

        error_indication, error_status, error_index, var_binds = cmd.getCmd(
            cmdgen.CommunityData('public', mpModel=0),
            cmdgen.UdpTransportTarget((self.ip, 161)), cmdgen.MibVariable(oid))

        if not error_indication and not error_status:
            result = float(var_binds[0][1]._value)

        if result < 50:
            result = (float(result) * (9.0 / 5.0)) + 32.0

        return result
Ejemplo n.º 27
0
    def walk(self, oid, subindex=None, timeout=3, retries=1, **kwargs):
        # logger.info("[SNMP] WALK oid, subindex %r %r", oid, subindex)
        if len(oid) == 2:
            mib, symbol = oid
            # logger.info("[SNMP] WALK mib, symbol %r %r", mib, symbol)
            mibVariable = cmdgen.MibVariable(mib, symbol).loadMibs(mib)
            # logger.info("[SNMP] WALK mibVariable1 %r", mibVariable)
            mibVariable.resolveWithMib(self.mibViewController)
            # logger.info("[SNMP] WALK mibVariable2 %r", mibVariable)
            oid_to_walk = mibVariable.asTuple()
            # logger.info("[SNMP] WALK oid_to_walk %r", oid_to_walk)
        else:
            oid_to_walk = oid

        if subindex:
            oid_to_walk += subindex

        data = self._next_cmd_data(oid_to_walk, timeout, retries, **kwargs)
        # logger.info("[SNMP] WALK data -> %d", len(data))

        raw = []
        for oid, value in data:
            # logger.info("[SNMP] WALK oid, value %s %s", oid, value)
            mv = self.get_resolved_mib_variable(oid)
            modName, symName, indices = mv.getMibSymbol()
            # logger.info("[SNMP] WALK modName, symName, indices %s %s %s", modName, symName, indices)
            index_string = tuple([x.prettyPrint() for x in indices])
            # logger.info("[SNMP] WALK index_string %s", index_string)
            try:
                # print 'value %s %s %r --> %s' % (type(value), value,
                # mv.getMibNode().syntax,
                # mv.getMibNode().syntax.clone(value).prettyPrint())
                final_value = mv.getMibNode().syntax.clone(value).prettyPrint()
                # logger.info("[SNMP] WALK final_value %s", final_value)
            except AttributeError:
                symName += index_string
                final_value = "ERROR: %s -> %s" % (index_string, value.prettyPrint())
            # print 'walk oid', mib, symbol, oid, value, final_value, index_string

            try:
                i = [i for i, d in raw].index(index_string)
                # logger.info("[SNMP] WALK i %s", i)
                ti, td = raw[i]
                # logger.info("[SNMP] WALK ti, td %s %s", ti, td)
                td[symName] = utils.to_native(value)
            except Exception as exc:
                raw.append((index_string, {symName: final_value}, ))

        return raw
Ejemplo n.º 28
0
    def __init__(self, config):
        from pysnmp.entity.rfc3413.oneliner import cmdgen
        self.snmp = cmdgen.CommandGenerator()

        self.host = cmdgen.UdpTransportTarget((config[CONF_HOST], 161))
        self.community = cmdgen.CommunityData(config[CONF_COMMUNITY])
        self.baseoid = cmdgen.MibVariable(config[CONF_BASEOID])

        self.lock = threading.Lock()

        self.last_results = []

        # Test the router is accessible
        data = self.get_snmp_data()
        self.success_init = data is not None
Ejemplo n.º 29
0
    def performSNMPConnection(self, host, port=161, community='public'):
        snmpCmdGen = cmdgen.CommandGenerator()
        print "[+] Trying community name: %s " %(community)
        snmpTransportData = cmdgen.UdpTransportTarget((host, port))
        mib = cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0)
        error, errorStatus, errorIndex, binds = snmpCmdGen.getCmd(cmdgen.CommunityData(community), snmpTransportData, mib)

        if "No SNMP response" in str(error):
            raise PySnmpError(str(error))
        if error:
            # Check for errors and print out results
            return False
        else:
            print "[*] SNMP Success ... community name: %s " % (community)
            return True
Ejemplo n.º 30
0
    def _get_pdu_ports(self):
        """
        @summary: Helper method for getting PDU ports connected to PSUs of DUT

        The PDU ports connected to DUT must have hostname of DUT configured in port name/description.
        This method depends on this configuration to find out the PDU ports connected to PSUs of specific DUT.
        """
        if not self.pduType:
            logging.info('PDU type is unknown: pdu_ip {} dut {}'.format(
                self.controller, self.hostname))
            return

        max_lane = 5
        host_matched = False
        cmdGen = cmdgen.CommandGenerator()
        snmp_auth = cmdgen.CommunityData(self.snmp_rocommunity)

        for lane_id in range(1, max_lane + 1):
            pdu_port_base = self.PORT_NAME_BASE_OID[0:-1] + str(lane_id)

            errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd(
                snmp_auth,
                cmdgen.UdpTransportTarget((self.controller, 161)),
                cmdgen.MibVariable("." + pdu_port_base, ),
            )
            if errorIndication:
                logging.debug(
                    "Failed to get ports controlling PSUs of DUT, exception: "
                    + str(errorIndication))
            else:
                for varBinds in varTable:
                    for oid, val in varBinds:
                        current_oid = oid.prettyPrint()
                        current_val = val.prettyPrint()
                        if self.hostname.lower() in current_val.lower():
                            host_matched = True
                            # Remove the preceding PORT_NAME_BASE_OID, remaining string is the PDU port ID
                            self.pdu_ports.append(
                                current_oid.replace(pdu_port_base, ''))
                if host_matched:
                    self.map_host_to_lane(lane_id)
                    break
        else:
            logging.error(
                "{} device is not attached to any outlet of PDU {}".format(
                    self.hostname.lower(), self.controller))