Beispiel #1
0
def get_security_engine_id(logger, ir: InventoryRecord,
                           snmpEngine: SnmpEngine):
    observerContext: Dict[Any, Any] = {}

    transportTarget = UdpTransportTarget((ir.address, ir.port),
                                         timeout=UDP_CONNECTION_TIMEOUT)

    # Register a callback to be invoked at specified execution point of
    # SNMP Engine and passed local variables at execution point's local scope
    snmpEngine.observer.registerObserver(
        lambda e, p, v, c: c.update(securityEngineId=v["securityEngineId"]),
        "rfc3412.prepareDataElements:internal",
        cbCtx=observerContext,
    )

    # Send probe SNMP request with invalid credentials
    authData = UsmUserData("non-existing-user")

    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(
            snmpEngine,
            authData,
            transportTarget,
            ContextData(),
            ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
        ))

    # See if our SNMP engine received REPORT PDU containing securityEngineId
    securityEngineId = fetch_security_engine_id(observerContext,
                                                errorIndication)
    logger.debug(f"securityEngineId={securityEngineId}")
    return securityEngineId
Beispiel #2
0
 def test_snmp(target, port=161, community='public'):
     try:
         errorIndication, errorStatus, errorIndex, varBinds = next(
             getCmd(SnmpEngine(),
                    # mpModel -> 0:v1,1:v2c
                    CommunityData(community, mpModel=1),
                    UdpTransportTarget(
                        (target, int(port)), timeout=1, retries=1),
                    ContextData(),
                    ObjectType(ObjectIdentity(
                        'SNMPv2-MIB', 'sysDescr', 0)),
                    ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0)))
         )
         if errorIndication:
             return (False, errorIndication)
         elif errorStatus:
             msg = '%s at %s' % (errorStatus.prettyPrint(
             ), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
             return (False, msg)
         else:
             result = []
             for varBind in varBinds:
                 result.append(' = '.join(
                     [x.prettyPrint() for x in varBind]))
             return (True, result)
     except Exception as e:
         # raise
         return (False, str(e))
Beispiel #3
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the SNMP sensor."""
    from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                              UdpTransportTarget, ContextData, ObjectType,
                              ObjectIdentity)

    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT, DEFAULT_PORT)
    community = config.get(CONF_COMMUNITY, DEFAULT_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(), CommunityData(community, mpModel=0),
               UdpTransportTarget((host, port)), ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication:
        _LOGGER.error('Please check the details in the configuration file')
        return False
    else:
        data = SnmpData(host, port, community, baseoid)
        add_devices([
            SnmpSensor(data, config.get('name', DEFAULT_NAME),
                       config.get('unit_of_measurement'))
        ])
    def _get(self, obj_identity):
        args = self.snmp_basic_info + (hlapi.ObjectType(obj_identity),)

        kwargs = {'lexicographicMode': False}

        result = {}

        for (errorIndication,
             errorStatus,
             errorIndex,
             varBinds) in hlapi.getCmd(*args, **kwargs):
            if errorIndication:
                print(errorIndication)
                break
            elif errorStatus:
                print('%s at %s' % (errorStatus.prettyPrint(),
                                    errorIndex and
                                    varBinds[int(errorIndex) - 1][0] or '?'))
                break
            else:
                for varBind in varBinds:
                    res = self._parse_var_bind(varBind)
                    value = varBind[1]
                    if isinstance(value, rfc1902.Integer32):
                        result[res[1]] = int(res[2])
                    else:
                        result[res[1]] = varBind[1]._value.decode('utf-8')

        return result
Beispiel #5
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the SNMP sensor."""
    from pysnmp.hlapi import (
        getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData,
        ObjectType, ObjectIdentity)

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    version = config.get(CONF_VERSION)

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(),
               CommunityData(community, mpModel=SNMP_VERSIONS[version]),
               UdpTransportTarget((host, port)),
               ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication:
        _LOGGER.error("Please check the details in the configuration file")
        return False
    else:
        data = SnmpData(host, port, community, baseoid, version)
        add_devices([SnmpSensor(data, name, unit)])
    def _oid_get(self, oid):
        """
        Performs SNMP get command and returns OID value by sending a SNMP Get message.

        Args:
            oid (str): Full OID identifying the object to be read.

        Return:
            OID value (int)
        """
        errorIndication, errorStatus, errorIndex, varBinds = next(
            getCmd(self._snmp_engine, self._community_data,
                   self._udp_transport_target, self._context,
                   ObjectType(ObjectIdentity(oid))))

        if errorIndication:
            msg = 'Found PDU errorIndication: {}'.format(errorIndication)
            logger.exception(msg)
            raise RuntimeError(msg)
        elif errorStatus:
            msg = 'Found PDU errorStatus: {}'.format(errorStatus)
            logger.exception(msg)
            raise RuntimeError(msg)

        return int(str(varBinds[-1]).partition('= ')[-1])
    def update(self):
        """Get the latest data from the remote SNMP capable host."""
        from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                                  UdpTransportTarget, ContextData, ObjectType,
                                  ObjectIdentity)
        from brother_ql.reader import interpret_response
        errindication, errstatus, errindex, restable = next(
            getCmd(SnmpEngine(), CommunityData(self._community, mpModel=0),
                   UdpTransportTarget((self._host, self._port)), ContextData(),
                   ObjectType(ObjectIdentity(self._baseoid))))

        if errindication:
            _LOGGER.error("SNMP error: %s", errindication)
        elif errstatus:
            _LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(),
                          errindex and restable[-1][int(errindex) - 1] or '?')
        else:
            assert len(restable) == 1
            status = interpret_response(bytes(restable[0][1]))
            self.media_type = status['media_type']
            self.media_width = '{} mm'.format(status['media_width'])
            self.media_length = status['media_length'] or 'endless'
            self.phase = status['phase_type']
            self.errors = ', '.join(status['errors']) or '-none-'
            if status['errors']:
                self.state = 'error'
            elif 'waiting' in status['phase_type'].lower():
                self.state = 'idle'
            elif 'printing' in status['phase_type'].lower():
                self.state = 'printing'
            else:
                self.state = STATE_UNKNOWN
Beispiel #8
0
    def update(self):
        """Update the state."""
        from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                                  UdpTransportTarget, ContextData, ObjectType,
                                  ObjectIdentity)

        from pyasn1.type.univ import (Integer)

        request = getCmd(SnmpEngine(),
                         CommunityData(self._community, mpModel=self._version),
                         UdpTransportTarget((self._host, self._port)),
                         ContextData(),
                         ObjectType(ObjectIdentity(self._baseoid)))

        errindication, errstatus, errindex, restable = next(request)

        if errindication:
            _LOGGER.error("SNMP error: %s", errindication)
        elif errstatus:
            _LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(),
                          errindex and restable[-1][int(errindex) - 1] or '?')
        else:
            for resrow in restable:
                if resrow[-1] == Integer(self._payload_on):
                    self._state = True
                elif resrow[-1] == Integer(self._payload_off):
                    self._state = False
                else:
                    self._state = None
Beispiel #9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the SNMP sensor."""
    from pysnmp.hlapi import (
        getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData,
        ObjectType, ObjectIdentity)

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    version = config.get(CONF_VERSION)
    accept_errors = config.get(CONF_ACCEPT_ERRORS)
    default_value = config.get(CONF_DEFAULT_VALUE)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.hass = hass

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(),
               CommunityData(community, mpModel=SNMP_VERSIONS[version]),
               UdpTransportTarget((host, port)),
               ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication and not accept_errors:
        _LOGGER.error("Please check the details in the configuration file")
        return False
    else:
        data = SnmpData(
            host, port, community, baseoid, version, accept_errors,
            default_value)
        add_devices([SnmpSensor(data, name, unit, value_template)], True)
Beispiel #10
0
    def _autodetect(self):
        from pysnmp import hlapi

        for (errorIndication, errorStatus, errorIndex,
             varBindTable) in hlapi.getCmd(
                 hlapi.SnmpEngine(), hlapi.CommunityData('public'),
                 hlapi.UdpTransportTarget((self.hostname, 161)),
                 hlapi.ContextData(),
                 hlapi.ObjectType(
                     hlapi.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))):
            if errorIndication:
                Exception("snmp error {}".format(errorIndication))
            elif errorStatus:
                Exception("snmp error {}".format(errorStatus))
            else:
                sysDescr = str(varBindTable[0][1])

        if sysDescr.startswith("HPE OfficeConnect Switch 1820 24G J9980A,"):
            self._get_fdb = self._get_fdb_dot1q
        elif sysDescr.startswith("HP 1810-24G,"):
            self._get_fdb = self._get_fdb_dot1d
        else:
            Exception("unsupported switch {}".format(sysDescr))

        self.logger.debug("autodetected switch{}: {} {}".format(
            sysDescr, self._get_ports, self._get_fdb))
Beispiel #11
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the SNMP sensor."""
    from pysnmp.hlapi import (
        getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData,
        ObjectType, ObjectIdentity)

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    version = config.get(CONF_VERSION)

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(),
               CommunityData(community, mpModel=SNMP_VERSIONS[version]),
               UdpTransportTarget((host, port)),
               ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication:
        _LOGGER.error("Please check the details in the configuration file")
        return False
    else:
        data = SnmpData(host, port, community, baseoid, version)
        add_devices([SnmpSensor(data, name, unit)])
def get_snmp_with_auth(template_oids, ip, port, user_name, authen_protocol,
                       authen_password, priv_protocol, priv_password, timeout,
                       retries):
    """
    :param template_oids:
    :param ip:
    :param port:
    :param user_name:
    :param authen_protocol:
    :param authen_password:
    :param priv_protocol:
    :param priv_password:
    :param timeout:
    :param retries:
    :return:
            errorIndication, errorStatus, errorIndex, varBinds
    """
    return next(
        getCmd(
            SnmpEngine(),
            UsmUserData(
                user_name,
                authKey=process_password.decrypt_password(
                    empty_to_none(authen_password)),
                privKey=process_password.decrypt_password(
                    empty_to_none(priv_password)),
                authProtocol=AUTH_PROTOCOL[empty_to_none(authen_protocol)],
                privProtocol=PRIV_PROTOCOL[empty_to_none(priv_protocol)]),
            UdpTransportTarget((ip, port), timeout=timeout, retries=retries),
            ContextData(), *template_oids))
Beispiel #13
0
    def get(self,
            target,
            oids,
            community,
            port=161,
            version=1,
            timeout=1,
            retries=3,
            engine=hlapi.SnmpEngine(),
            context=hlapi.ContextData()):
        try:
            handler = hlapi.getCmd(
                engine, hlapi.CommunityData(community, mpModel=version),
                hlapi.UdpTransportTarget((target, port),
                                         timeout=timeout,
                                         retries=retries), context,
                *self._construct_object_types(oids))
        except Exception as e:
            print('> get : ', e)
            traceback.print_exc(file=sys.stdout)
            return -1

        fetch_value = self._fetch(handler, 1)

        if fetch_value != -1:
            return fetch_value[0]
        else:
            return fetch_value
Beispiel #14
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the SNMP sensor."""
    from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                              UdpTransportTarget, ContextData, ObjectType,
                              ObjectIdentity)

    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT, DEFAULT_PORT)
    community = config.get(CONF_COMMUNITY, DEFAULT_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(),
               CommunityData(community, mpModel=0),
               UdpTransportTarget((host, port)),
               ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication:
        _LOGGER.error('Please check the details in the configuration file')
        return False
    else:
        data = SnmpData(host, port, community, baseoid)
        add_devices([SnmpSensor(data,
                                config.get('name', DEFAULT_NAME),
                                config.get('unit_of_measurement'))])
def snmpGet(snmpVersion, community, host, port, oids):

    logging.info('New Get Query [v:%d, %s, %s, %d, %s]', snmpVersion,
                 community, host, port, oids)

    objectTypes = [snmp.ObjectType(snmp.ObjectIdentity(oid)) for oid in oids]

    errorIndication, errorStatus, errorIndex, varBinds = next(
        snmp.getCmd(snmp.SnmpEngine(),
                    snmp.CommunityData(community, mpModel=snmpVersion),
                    snmp.UdpTransportTarget((host, port)), snmp.ContextData(),
                    *objectTypes))

    if errorIndication:
        logging.error(errorIndication)
        return None

    if errorStatus:
        logging.error('%s at %s', errorStatus.prettyPrint(),
                      errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
        return None

    results = [(str(name), str(value)) for name, value in varBinds]

    return dict(results)
Beispiel #16
0
def get_node(conn):
    node = {}
    name = SnmpApi.ObjectType(
        SnmpApi.ObjectIdentity('SNMPv2-MIB', 'sysName', 0))
    descr = SnmpApi.ObjectType(
        SnmpApi.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))

    errorIndication, errorStatus, errorIndex, varBinds = next(
        SnmpApi.getCmd(conn['snmpEng'], conn['community'], conn['target'],
                       conn['context'], name, descr))

    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for varBind in varBinds:
            (oid, value) = [x.prettyPrint() for x in varBind]
            if value is None:
                continue

            if re.search('sysName', oid):
                node['name'] = value
            elif re.search('sysDescr', oid):
                node['descr'] = value

    return node
Beispiel #17
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the SNMP sensor."""
    from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                              UdpTransportTarget, ContextData, ObjectType,
                              ObjectIdentity)

    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    version = config.get(CONF_VERSION)
    accept_errors = config.get(CONF_ACCEPT_ERRORS)
    default_value = config.get(CONF_DEFAULT_VALUE)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.hass = hass

    errindication, _, _, _ = next(
        getCmd(SnmpEngine(),
               CommunityData(community, mpModel=SNMP_VERSIONS[version]),
               UdpTransportTarget((host, port)), ContextData(),
               ObjectType(ObjectIdentity(baseoid))))

    if errindication and not accept_errors:
        _LOGGER.error("Please check the details in the configuration file")
        return False
    else:
        data = SnmpData(host, port, community, baseoid, version, accept_errors,
                        default_value)
        add_devices([SnmpSensor(data, name, unit, value_template)], True)
Beispiel #18
0
def query_snmp_interface(oid, host="localhost", port=1024):
    """Helper function to query snmp interface of a device"""
    error_indicator, error_status, error_idx, var_binds = next(
        hlapi.getCmd(
            hlapi.SnmpEngine(),
            hlapi.CommunityData("private", mpModel=0),
            hlapi.UdpTransportTarget((host, port)),
            hlapi.ContextData(),
            hlapi.ObjectType(hlapi.ObjectIdentity(oid)),
            lookupMib=False,
        )
    )

    if error_indicator:
        print(error_indicator)
    elif error_status:
        print(
            "%s at %s"
            % (
                error_status.prettyPrint(),
                error_idx and var_binds[int(error_idx) - 1][0] or "?",
            )
        )
    else:
        v_bind = var_binds[0]
        return v_bind[1]

    return None
Beispiel #19
0
 def outlet_state(self, set_state=None):
     '''The current state of the outlet. Setting this value to turnOff(1)
     will turn off the outlet. Setting this value to turnOn(2) will turn on
     the outlet. Setting this value to cycle(3) will turn the outlet off, 
     then turn it back on:
         0 = idle or unknown
         1 = off
         2 = on
         3 = cycle (turn off, then turn on
     '''
     if set_state is None:
         # Get current outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletState',
                                         self.device_id, self.outlet_id)
         g = getCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(), rfc1902.ObjectType(obj_id))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
         oid, value = varBinds[0]
         return int(value)
     else:
         # Send outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletCommand',
                                         self.device_id, self.outlet_id)
         g = setCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(),
                    rfc1902.ObjectType(obj_id, int(set_state)))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
Beispiel #20
0
 def get(self, oids, engine=hlapi.SnmpEngine(),
         context=hlapi.ContextData()):
     handler = hlapi.getCmd(
         engine, self.credentials,
         hlapi.UdpTransportTarget((self.target, self.port)), context,
         *construct_object_types(oids))
     return self.fetch(handler, 1)[0]
Beispiel #21
0
    def get(self, oid):
        """Use PySNMP to perform an SNMP GET operation on a single object.

        :param oid: The OID of the object to get.
        :raises: SNMPFailure if an SNMP request fails.
        :returns: The value of the requested object.
        """
        try:
            snmp_gen = snmp.getCmd(self.snmp_engine,
                                   self._get_auth(),
                                   self._get_transport(),
                                   self._get_context(),
                                   snmp.ObjectType(snmp.ObjectIdentity(oid)))

        except snmp_error.PySnmpError as e:
            raise exception.SNMPFailure(operation="GET", error=e)

        error_indication, error_status, error_index, var_binds = next(snmp_gen)

        if error_indication:
            # SNMP engine-level error.
            raise exception.SNMPFailure(operation="GET",
                                        error=error_indication)

        if error_status:
            # SNMP PDU error.
            raise exception.SNMPFailure(operation="GET",
                                        error=error_status.prettyPrint())

        # We only expect a single value back
        name, val = var_binds[0]
        return val
Beispiel #22
0
def probe_oper_status(player):
    switch = current_app.config['SWITCHES'][player]
    address = switch['address']
    port = switch['port']
    logger.info("Probing status for player %d on switch %s:%d", player,
                address)
    engine = SnmpEngine()
    auth_data = CommunityData(switch['community'], mpModel=1)
    transport = UdpTransportTarget((address, port))
    interfaces = switch['interfaces']
    oper_states = []
    for chunk in chunked(
        (ObjectType(ObjectIdentity(ifOperStatus.oid + (index, )), Null())
         for index in interfaces), 24):
        cmd = getCmd(engine, auth_data, transport, ContextData(), *chunk)
        errorIndication, errorStatus, errorIndex, varBinds = next(cmd)
        if errorIndication is not None:
            raise Exception("SNMP error returned")
        oper_states.extend(
            ifOperStatus(int(value)) for identity, value in varBinds)
    with StateLock:
        for cell_state, (index,
                         oper_state) in zip(current_app.cell_state[player],
                                            enumerate(oper_states)):
            if oper_state == ifOperStatus.down and cell_state != CellState.EMPTY:
                current_app.cell_state[player][index] = CellState.PRESENT

            if oper_state == ifOperStatus.up and cell_state != CellState.EMPTY:
                current_app.cell_state[player][index] = CellState.HIT
        if not any(cell_state == CellState.PRESENT
                   for cell_state in current_app.cell_state[player]):
            current_app.game_state = GameState.OVER
            return True
    return False
Beispiel #23
0
def snmp_harvester(ip: str, port: int, community: str,
                   parameters: typing.Iterable[str]) -> t_snmp_samples_chunk:
    """
    Fires SNMP GET query at endpoint defined by ip and port. The query
    consists all of OIDs defined in parameters argument.

    :param ip: host IP address
    :param port: SNMP port number
    :param community: community name
    :param parameters: list of OIDs
    :returns: samples as list of pairs: OID and its collected value
    """
    if ipaddress.ip_address(ip).version == 4:
        transport = UdpTransportTarget
    else:
        transport = Udp6TransportTarget

    result = getCmd(SnmpEngine(), CommunityData(community, mpModel=1),
                    transport((ip, port)), ContextData(),
                    *[ObjectType(ObjectIdentity(oid)) for oid in parameters])

    _error_indication, _error_status, _error_index, var_binds = next(result)

    return [(str(name), value._value) for name, value in var_binds
            if not isinstance(value, Null)]
Beispiel #24
0
    def update(self):
        """Update the state."""
        from pysnmp.hlapi import (
            getCmd, CommunityData, SnmpEngine, UdpTransportTarget, ContextData,
            ObjectType, ObjectIdentity)

        from pyasn1.type.univ import (Integer)

        request = getCmd(
            SnmpEngine(),
            CommunityData(self._community, mpModel=self._version),
            UdpTransportTarget((self._host, self._port)),
            ContextData(),
            ObjectType(ObjectIdentity(self._baseoid))
        )

        errindication, errstatus, errindex, restable = next(request)

        if errindication:
            _LOGGER.error("SNMP error: %s", errindication)
        elif errstatus:
            _LOGGER.error("SNMP error: %s at %s", errstatus.prettyPrint(),
                          errindex and restable[-1][int(errindex) - 1] or '?')
        else:
            for resrow in restable:
                if resrow[-1] == Integer(self._payload_on):
                    self._state = True
                elif resrow[-1] == Integer(self._payload_off):
                    self._state = False
                else:
                    self._state = None
Beispiel #25
0
 def get_cmd(self, oid):
     """
     SNMP get
     """
     snmp_ret = getCmd(SnmpEngine(), self.get_auth(),
                       UdpTransportTarget((self.hostname, self.snmp_port)),
                       ContextData(), ObjectType(ObjectIdentity(oid)))
     return self._to_list(snmp_ret=snmp_ret)
def get(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()):
    handler = hlapi.getCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *construct_object_types(oids)
    )
    return fetch(handler, 1)[0]
def find_router_type(host, port):
    oid = '.1.3.6.1.2.1.1.1.0'
    #import pysnmp.hlapi as ph
    g = ph.getCmd(
        ph.SnmpEngine(), ph.CommunityData('otauB9v1kYRO'),
        ph.UdpTransportTarget((host, port)), ph.ContextData(),
        ph.ObjectType(ph.ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
    nextg = next(g)
    print(nextg)
 def get(self, oids):
     handler = hlapi.getCmd(
         hlapi.SnmpEngine(),
         hlapi.UsmUserData(userName=self.username,
                           authKey=self.authKey,
                           privKey=self.privKey,
                           authProtocol=self.authProtocol,
                           privProtocol=self.privProtocol),
         hlapi.UdpTransportTarget((self.host, 161)), hlapi.ContextData(),
         *self.__construct_object_types(oids))
     return self.__fetch(handler, 1)[0]
Beispiel #29
0
 def get_cmd(self, oid):
     '''
     get oid mib info
     '''
     self.snmp_ret = getCmd(SnmpEngine(),
                            self.get_auth(),
                            UdpTransportTarget(
                                (self.router_ip, self.snmp_port)),
                            ContextData(),
                            ObjectType(ObjectIdentity(oid)))
     return self._to_list()
Beispiel #30
0
 def get_by_oid(self, oid):
     res = hlapi.getCmd(
         hlapi.SnmpEngine(),
         self.auth_data,
         hlapi.UdpTransportTarget(self.target),
         hlapi.ContextData(),
         hlapi.ObjectType(hlapi.ObjectIdentity(oid)),
     )
     res = next(res)
     err_indication, err_status, err_index, var_binds = res
     return var_binds[0]
Beispiel #31
0
def _make_get(address, community, *objects, port=161, mp_model=1):
    """Construct a pySNMP get command.

    Defaults to SNMPv2c and port 161.

    """
    engine = hlapi.SnmpEngine()
    community = hlapi.CommunityData(community, mpModel=mp_model)
    target = hlapi.UdpTransportTarget((address, port))
    context = hlapi.ContextData()
    return hlapi.getCmd(engine, community, target, context, *objects)
Beispiel #32
0
    def get(self, oid):
        g = hlapi.getCmd(self.engine,
                         self.community,
                         self.transport,
                         self.context,
                         hlapi.ObjectType(hlapi.ObjectIdentity(oid)),
                         lookupMib=False)

        error_indication, error_status, _, res = next(g)
        if error_indication or error_status:
            raise ExecutionError("Failed to get SNMP value")
        return res[0][1]
Beispiel #33
0
def get_name(ip):
    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(SnmpEngine(), CommunityData(community, mpModel=0),
               UdpTransportTarget((ip, 161)), ContextData(),
               ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0'))))
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        for oid, value in varBinds:
            return value
Beispiel #34
0
    def get_by_var(self, mib_name, var_name, position=None):
        oid = ((mib_name, var_name) if position is None else
               (mib_name, var_name, position))

        res = hlapi.getCmd(
            hlapi.SnmpEngine(),
            self.auth_data,
            hlapi.UdpTransportTarget(self.target),
            hlapi.ContextData(),
            hlapi.ObjectType(hlapi.ObjectIdentity(*oid)),
        )
        res = next(res)
        err_indication, err_status, err_index, var_binds = res
        return var_binds[0]
Beispiel #35
0
    def update(self):
        """Get the latest data from the remote SNMP capable host."""
        from pysnmp.hlapi import (getCmd, CommunityData, SnmpEngine,
                                  UdpTransportTarget, ContextData, ObjectType,
                                  ObjectIdentity)
        errindication, errstatus, errindex, restable = next(
            getCmd(SnmpEngine(),
                   CommunityData(self._community, mpModel=0),
                   UdpTransportTarget((self._host, self._port)),
                   ContextData(),
                   ObjectType(ObjectIdentity(self._baseoid)))
            )

        if errindication:
            _LOGGER.error("SNMP error: %s", errindication)
        elif errstatus:
            _LOGGER.error('SNMP error: %s at %s', errstatus.prettyPrint(),
                          errindex and restable[-1][int(errindex) - 1] or '?')
        else:
            for resrow in restable:
                self.value = resrow[-1]