示例#1
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)])
示例#2
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
示例#3
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)
    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
示例#5
0
    def _create_cmd_generator(self, object_identity, cmd_command):
        """
        Generates the getCmd (see pySNMP doc) required to retrieve information from the agent.

        :raises: SnmpVersionException: if the SNMP version specified is not valid.

        :param object_identity: pySNMP object identity corresponding to the information we are looking for
        :return: cmd_command result
        """

        if self.snmp_version == 1 or self.snmp_version == 2:
            data = CommunityData(self.community_index,
                                 mpModel=self.snmp_version - 1)
            return cmd_command(
                SnmpEngine(),
                data,
                UdpTransportTarget((self.server_address, self.snmp_port)),
                ContextData(),
                ObjectType(object_identity),
                lexicographicMode=False
            )  # STOPS WALKS WITHOUT CROSSING BOUNDARIES # EXAMPLE: IF WE GIVE OID 1.3.6.1.2.1.25.4.2.1.2, WE WILL ONLY WALK 1.3.6.1.2.1.25.4.2.1.2.X VALUES. IF THIS IS TRUE, WE WALK THE WHOLE TREE AFTER 1.3.6.1.2.1.25.4.2.1.2

        SNMP_LOGGER.error(
            "SNMPv%d does not currently exist or isn't supported by this query",
            self.snmp_version)
        raise SnmpVersionException(
            "SNMPv%d does not currently exist or isn't supported by this query"
            % self.snmp_version)
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))
def define_request(source, ip, community, snmp_version, fileconfname, pathfile,
                   protocol, srvprovision, enableconfstart, urlfirmware,
                   enablereboot):
    if snmp_version == '2c':
        communityData = CommunityData(community, mpModel=1)
    if snmp_version == '1':
        communityData = CommunityData(community, mpModel=0)
    if source:
        assd = AsynsockDispatcher()
        sock_transport = udp.UdpSocketTransport()
        sock_transport.socket.setsockopt(socket.SOL_SOCKET, 25, source + '\0')
        snmp_engine = engine.SnmpEngine()
        assd.registerTransport(udp.domainName, sock_transport)
        snmp_engine.registerTransportDispatcher(assd)
    else:
        snmp_engine = engine.SnmpEngine()
    varBind = []
    result = []
    for errorIndication, errorStatus, errorIndex, varBinds in setCmd(
            snmp_engine, communityData, UdpTransportTarget((ip, 161)),
            ContextData(),
            ObjectType(
                ObjectIdentity(
                    '1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.100.0'),
                OctetString(fileconfname)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.300.0'),
                OctetString(pathfile)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.100.0'),
                Integer32(protocol)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.400.400.0'),
                OctetString(srvprovision)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.800.1.100.500.100.0'),
                Integer32(enableconfstart)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.450.0'),
                OctetString(urlfirmware)),
            ObjectType(
                ObjectIdentity(
                    '.1.3.6.1.4.1.4935.1000.100.200.100.1300.1.500.0'),
                Integer32(enablereboot))):
        varBind.append(varBinds)
        for i in varBinds:
            i = str(i)
            i = i.split('=')[1]
            result.append(i)


#             result.append(str(i))
#             varBind = varBind.split('=')[1]
#             result.append(varBind)
    return result
示例#8
0
文件: snmp.py 项目: SrijaGupta/file
    def __init__(self, kwargs):
        snmp_channel_id = kwargs.get('channel_id', \
                                     str(os.getpid()) + \
                                     str(time.time()).split('.')[0] + \
                                     str(random.randint(0, 9)) \
                                     )
        self.snmpchannel = SnmpEngine(snmpEngineID=snmp_channel_id)
        self.timeout = kwargs.get('timeout', 60)
        self.mibs_dir = kwargs.get('MIBDIRS', DEFAULT_MIBDIR)
        self.mibs_custom_dir = kwargs.get('mibs_custom_dir', None)
        if self.mibs_custom_dir:
            t.log('mibs_custom_dir: '+self.mibs_custom_dir)
        self.community = kwargs.get('community', 'public')
        self.version = kwargs.get('version', 2)
        self.host = kwargs.get('host')
        # SNMP V3 settings
        self.group = kwargs.get('group')
        self.user = kwargs.get('user', 'test1')
        self.auth_type = kwargs.get('auth_type', 'usmHMACSHAAuthProtocol')
        self.auth_pass = kwargs.get('auth_pass', 'test1234')
        self.priv_type = kwargs.get('priv_type', 'usmAesCfb128Protocol')
        self.priv_pass = kwargs.get('priv_pass', 'test1234')
        self.context_engine = kwargs.get('context_engine', None)
        self.context_name = kwargs.get('context_name', '')

        self.port = kwargs.get('port', 161)
        self.transport = UdpTransportTarget((self.host, self.port))

        self.aindex = 1
        self.eindex = 8

        self.trap_port = kwargs.get('trap_port', self.get_free_port())
        self.trap_server_v4 = kwargs.get('trap_server_v4', 'localhost')
        self.trap_server_v6 = kwargs.get('trap_server_v6', '::1')
示例#9
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'))
        ])
示例#10
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
示例#11
0
def _snmp_walk(host, community, oid):
    assert host, "host must be defined."
    assert community, "community must be defined."
    assert oid, "oid must be defined."
    assert isinstance(oid, ObjectType), "oid must be of ObjectType"

    for errorIndication, errorStatus, errorIndex, varBinds in nextCmd(
            SnmpEngine(),
            CommunityData(community, mpModel=1),
            UdpTransportTarget((host, 161)),
            ContextData(),
            oid,
            ignoreNonIncreasingOid=True,
            lookupMib=True,
            lexicographicMode=False):

        if errorIndication:
            logger.error(errorIndication)
        else:
            if errorStatus:
                raise Exception('%s at %s' % (
                    errorStatus.prettyPrint(),
                    errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            else:
                for name, val in varBinds:
                    yield name.prettyPrint(), val.prettyPrint()
示例#12
0
    def _walk(self):
        """SNMP Walk

        Returns:
            Dictionary with configurations fetched via SNMP.

        """
        iterator = nextCmd(
            self.engine, CommunityData('public'),
            UdpTransportTarget((self.address, self.port)), ContextData(),
            ObjectType(
                ObjectIdentity(self.mib, '', 0).addMibSource(self.mib_dir)))
        res = {}
        for errorIndication, errorStatus, errorIndex, varBinds in iterator:
            if errorIndication:
                logger.error(errorIndication)
            elif errorStatus:
                logger.error(
                    '%s at %s' %
                    (errorStatus.prettyPrint(),
                     errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
            else:
                for varBind in varBinds:
                    logger.debug(varBind)
                    varBindList = [x.prettyPrint() for x in varBind]
                    key = varBindList[0].replace(self.mib + "::", "")
                    if (len(varBindList) > 2):
                        res[key] = tuple(varBindList[1:])
                    else:
                        res[key] = varBindList[1]
        return res
示例#13
0
    def update(self):
        """Get the latest data from the remote SNMP capable host."""
        from pysnmp.hlapi import (nextCmd, CommunityData, SnmpEngine,
                                  UdpTransportTarget, ContextData, ObjectType,
                                  ObjectIdentity)
        for errindication, errstatus, errindex, restable in nextCmd(
                SnmpEngine(),
                CommunityData(self._community, mpModel=self._version),
                UdpTransportTarget((self._host, self._port)), ContextData(),
                ObjectType(ObjectIdentity(self._baseoid))):
            if errindication and not self._accept_errors:
                _LOGGER.error("SNMP error: %s", errindication)
            elif errstatus and not self._accept_errors:
                _LOGGER.error(
                    "SNMP error: %s at %s", errstatus.prettyPrint(),
                    errindex and restable[-1][int(errindex) - 1] or '?')
            elif (errindication or errstatus) and self._accept_errors:
                self.value = self._default_value
            else:
                for resrow in restable:
                    self.attributes[str(resrow[0])] = resrow

        self.value = self._default_value

        errors = self.attributes.get('1.3.6.1.2.1.25.3.5.1.2.1')
        if errors:
            code = errors[1].asNumbers()[0]
            if code != 0:
                _LOGGER.info('Error code: %s', errors[1].asNumbers())
                self.value = ERRORS.get(int(math.log(code, 2)))
                return

        status = self.attributes.get('1.3.6.1.2.1.25.3.5.1.1.1')
        if status:
            self.value = STATUS.get(status[-1])
示例#14
0
    def set_outlet_on(self, outlet, on):
        """
        Set an outlet on or off

        :param outlet: Which outlet to set the power for (for my model this is
                       in the range 1 through 8)
        :param on: INVALID ATM True means turn it on, False means turn it off
        """

        oid = ObjectIdentity(
            "1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.{}".format(outlet))
        if isinstance(on, bool):
            target_state = "immediateOn" if on else "immediateOff"
        else:
            target_state = on

        errorIndication, errorStatus, errorIndex, varBinds = next(
            setCmd(
                SnmpEngine(),
                CommunityData("private"),
                UdpTransportTarget((self.host, 161)),
                ContextData(),
                ObjectType(oid,
                           Integer32(self.outlet_state_oids[target_state])),
            ))

        if errorIndication:
            raise CyberPowerPduException(errorIndication)
        elif errorStatus:
            raise CyberPowerPduException("%s at %s" % (
                errorStatus.prettyPrint(),
                errorIndex and varBinds[int(errorIndex) - 1][0] or "?",
            ))
示例#15
0
def get_snmp_table_data(config,
                        *args,
                        snmp_engine=SnmpEngine(),
                        snmpversion="2c"):
    """Retrieve necessary data via SNMP"""

    authdata = prepare_authdata(config, snmpversion)

    target = UdpTransportTarget((config["host"], config["port"]))

    snmp_data = []
    for (error_indication, error_status, error_index, var_binds) in nextCmd(
            snmp_engine,
            authdata,
            target,
            ContextData(),
            *args,
            lexicographicMode=False,
    ):
        if error_indication:
            raise ValueError(error_indication)
        elif error_status:
            status = error_status.prettyPrint()
            index = error_index and var_binds[int(error_index) - 1][0] or "?"
            raise ValueError(f"{status} at {index}")
        else:
            snmp_data.append(var_binds)
    return snmp_data
示例#16
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
示例#17
0
 def trap_v3(self, endpoint, message):
     # Send trap to one endpoint
     error_indication, error_status, error_index, var_binds = next(
         sendNotification(
             SnmpEngine(snmpEngineID=OctetString(
                 hexValue=endpoint.engineid)),
             endpoint.usm_user,
             UdpTransportTarget((endpoint.host, endpoint.port)),
             ContextData(),
             'trap',
             # sequence of custom OID-value pairs
             self.get_pdu(message)))
     if error_indication:
         log(
             "error",
             "notifier",
             {
                 "message": 'Unable to send snmp message to %s err:%s %s %s'
                 % (endpoint.host,
                    error_indication,
                    error_status,
                    error_index)
             }
         )
     else:
         log(
             "info",
             "notifier",
             {
                 "message": 'Sent snmp message to %s to alert about %s'
                 % (endpoint.host,
                    message)
             }
         )
示例#18
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))
示例#19
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)
示例#20
0
 def walk(self, oid):
     snmp_ret = nextCmd(SnmpEngine(),
                        CommunityData(self.community),
                        UdpTransportTarget((self.hostname, self.snmp_port)),
                        ContextData(),
                        ObjectType(ObjectIdentity(oid)),
                        lexicographicMode=False)
     return self._to_list(snmp_ret=snmp_ret)
示例#21
0
    def set_outlet_on(self, outlet, on):
        """
        Set an outlet on or off

        :param outlet: Which outlet to set the power for (for my model this is
                       in the range 1 through 8)
        :param on: True means turn it on, False means turn it off
        """
        # OK, sorry for this insane code - the pysnmp docs explicitly say you
        # should just copy paste their examples.
        # This is based on the code from here:
        # http://snmplabs.com/pysnmp/examples/hlapi/asyncore/sync/manager/cmdgen/modifying-variables.html

        # The command we would run to power on outlet 1 on the PDU, if we were
        # not masochists is this:
        #
        # snmpset -v 1 -c private $IPADDR CPS-MIB::ePDUOutletControlOutletCommand.1 i immediateOn
        #
        # However to get those human-readable names to work we'd need to
        # download MIBs and tell pysnmp about them. pysnmp + pysmi apparently
        # know how to do this but I tried to point it at the CyberPower MIB file
        # and it failed silently so huffed and gave up.
        #
        # So instead, we're going to do something more akin to this command,
        # which is exactly the same thing but without the human-readable names:
        #
        # snmpset -v 1 -c private $IPADDR .1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.2 i 1
        #
        # In that command ".1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.2" is the
        # masochistic name for "CPS-MIB::ePDUOutletControlOutletCommand.2" and
        # "1" is the masochistic name for "immediateOn"
        #
        # I figured out what that command would be by running this:
        # snmptranslate -On CPS-MIB::ePDUOutletControlOutletCommand
        #
        # SnmpEngine and ContextData are just pointless boilerplate required by
        # pysnmp.  Hopefully you can sort of see how the other bits map to the
        # code below (the "i" becaomse "Integer32").

        oid = ObjectIdentity(
            '1.3.6.1.4.1.3808.1.1.3.3.3.1.1.4.{}'.format(outlet))
        target_state = 'immediateOn' if on else 'immediateOff'
        errorIndication, errorStatus, errorIndex, varBinds = next(
            setCmd(
                SnmpEngine(), CommunityData('private'),
                UdpTransportTarget((self.host, 161)), ContextData(),
                ObjectType(oid,
                           Integer32(self.outlet_state_oids[target_state]))))

        if errorIndication:
            raise CyberPowerPduException(errorIndication)
        elif errorStatus:
            raise CyberPowerPduException(
                '%s at %s' %
                (errorStatus.prettyPrint(),
                 errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
示例#22
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()
示例#23
0
 def next_cmd(self, oid, max_rows=25, max_calls=0):
     '''
     get next oid mib info
     '''
     self.snmp_ret = nextCmd(SnmpEngine(),
                             CommunityData(self.community),
                             UdpTransportTarget(
                                 (self.router_ip, self.snmp_port)),
                             ContextData(),
                             ObjectType(ObjectIdentity(oid)),
                             maxRows=max_rows, maxCalls=max_calls)
     return self._to_list()
示例#24
0
    def _set(self, value):
        from pysnmp.hlapi import (setCmd, CommunityData, SnmpEngine,
                                  UdpTransportTarget, ContextData, ObjectType,
                                  ObjectIdentity)

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

        next(request)
示例#25
0
 def bulk_cmd(self, oid, non_repeaters=0, max_repeaters=1):
     '''
     bulk get router info by oid
     '''
     self.snmp_ret = bulkCmd(SnmpEngine(),
                             CommunityData(self.community),
                             UdpTransportTarget(
                                 (self.router_ip, self.snmp_port)),
                             ContextData(),
                             non_repeaters, max_repeaters,
                             ObjectType(ObjectIdentity(oid)),
                             maxCalls=10)
     return self._to_list(oid)
示例#26
0
    def do_GET(self):

        if "/?target=" not in self.path:
            self._set_headers_404()
            return ()

        self._set_headers()
        dest_host = self.path.split('=')[1]
        print('Target: ', dest_host)

        start_time = time.monotonic()
        self.wfile.write("\n".encode('utf-8'))

        auth_data = CommunityData(SNMP_COMMUNITY, mpModel=0)
        SNMP_target = UdpTransportTarget((dest_host, SNMP_UDP_PORT))

        response = "# TYPE ifOutOctets counter\n"
        users_stats = get_usage(auth_data, SNMP_target)
        for username in users_stats.keys():
            try:
                response = response + 'ifOutOctets{ user="******" } ' + str(
                    users_stats[username]['TX_Octets']) + '\n'
            except KeyError:
                pass

        response = response + "# TYPE ifInOctets counter\n"
        for username in users_stats.keys():
            try:
                response = response + 'ifInOctets{ user="******" } ' + str(
                    users_stats[username]['RX_Octets']) + '\n'
            except KeyError:
                pass

        response += "# TYPE sessionUpTime counter\n"
        for username in users_stats.keys():
            try:
                response += 'sessionUpTime{ user="******" } ' + str(
                    users_stats[username]['session_uptime'] / 100) + '\n'
            except KeyError:
                pass

        response = response + '# TYPE total_l2tp_sessions summary\n'
        response = response + 'total_l2tp_sessions ' + str(
            len(users_stats)) + '\n'

        response = response + '# TYPE request_processing_seconds summary\n'
        response = response + 'request_processing_seconds ' + str(
            time.monotonic() - start_time) + '\n'

        self.wfile.write(response.encode('utf-8'))
        self.wfile.write("\n".encode('utf-8'))
示例#27
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
示例#28
0
def snmpget(ipaddress, community, oid):
    iterator = getCmd(SnmpEngine(), CommunityData(community),
                      UdpTransportTarget((ipaddress, 161)), ContextData(),
                      ObjectType(ObjectIdentity(oid)))
    errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

    if errorIndication:
        raise Exception(f"Error performing snmpget: {errorIndication}")
    elif errorStatus:
        _msg = '%s at %s' % (errorStatus.prettyPrint(), errorIndex
                             and varBinds[int(errorIndex) - 1][0] or '?')
        raise Exception(f"Error performing snmpget: {_msg}")
    else:
        if len(varBinds) > 0:
            return varBinds
        return None
示例#29
0
 def test_snmp_works(self):
     for series in ['xenial', 'bionic', 'cosmic', 'disco']:
         status = zaza.model.get_status() \
             .applications['ubuntu-{}'.format(series)]
         for unit in status["units"]:
             details = status['units'][unit]
             address = details['public-address']
             errorIndication, errorStatus, errorIndex, varBinds = next(
                 getCmd(SnmpEngine(),
                        CommunityData('public'),
                        UdpTransportTarget((address, 161)),
                        ContextData(),
                        ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
                        ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')))
             )
             self.assertIsNone(errorIndication)
示例#30
0
 def __init__(self, ip_address, outlet_id, timeout=1, retries=5):
     self.mib = 'TRIPPLITE-PRODUCTS'
     self.transport_addr = (str(ip_address), 161)
     self.transport_target = UdpTransportTarget(self.transport_addr,
                                                timeout=timeout,
                                                retries=retries)
     self.outlet_id = int(outlet_id)
     self.device_id = 1
     self.community = CommunityData('tripplite')
     # Initialize the MIB
     mibBuilder = builder.MibBuilder()
     mibView = view.MibViewController(mibBuilder)
     obj_id = rfc1902.ObjectIdentity(self.mib)
     obj_id.addAsn1MibSource('file://@mib@')
     obj_id.addAsn1MibSource('http://mibs.snmplabs.com/asn1/@mib@')
     obj_id.resolveWithMib(mibView)