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
示例#2
0
 def trap_v2(self, endpoint, message):
     # Send trap to one endpoint
     error_indication, error_status, error_index, var_binds = next(
         sendNotification(
             SnmpEngine(snmpEngineID=OctetString(
                 hexValue=endpoint.engineid)),
             CommunityData(endpoint.community, mpModel=1),
             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)
             }
         )
示例#3
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()
示例#4
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))
示例#5
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
示例#6
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)])
示例#7
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)]
示例#8
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 "?",
            ))
示例#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 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
    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
示例#12
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)
示例#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 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)
示例#15
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
示例#16
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)
示例#17
0
 def get_auth_data(self):
     """ Returns the authentication data that is used in the SNMP
     command generator """
     if self.version != 3:
         return CommunityData(self.community)
     return UsmUserData(
         self.community, self.auth_passwd, self.priv_passwd,
         AUTH_PROTOCOLS.get(self.auth_type, AUTH_PROTOCOLS[AUTH_NONE]),
         PRIV_PROTOCOLS.get(self.priv_type, PRIV_PROTOCOLS[PRIV_NONE]))
示例#18
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 '?'))
示例#19
0
 def get_auth(self):
     '''
     get auth by snmp version
     '''
     auth = None
     if self.version == self.SNMP_VERSION_2C:
         auth = CommunityData(self.community)
     elif self.version == self.SNMP_VERSION_3:
         auth = UsmUserData(self.user_name,
                            authKey=self.auth_key, privKey=self.priv_key)
     return auth
示例#20
0
文件: snmp.py 项目: SrijaGupta/file
    def create_community_data(self, **kwargs):
        """
            :param version: SNMP Version. Default to 2
            :param user: UserID
            :param password: Password
            :return:
        """
        t.log("DEBUG", "Entering 'create_community_data'\n"+__file__)
        version = kwargs.get('version', self.version)
        user = kwargs.get('user', self.user)
        auth_type = kwargs.get('auth_type', self.auth_type)
        auth_pass = kwargs.get('auth_pass', self.auth_pass)
        priv_type = kwargs.get('priv_type', self.priv_type)
        priv_pass = kwargs.get('priv_pass', self.priv_pass)
        community = kwargs.get('community', self.community)

        valid_auth_type = ['usmHMACMD5AuthProtocol', 'usmHMACSHAAuthProtocol']
        valid_priv_type = ['usmDESPrivProtocol', 'usm3DESEDEPrivProtocol',
                           'usmAesCfb128Protocol', 'usmAesCfb192Protocol',
                           'usmAesCfb256Protocol']

        if version == 1:
            return_value = CommunityData(community, mpModel=0)
        elif version == 2:
            return_value = CommunityData(community)
        elif version == 3:
            if priv_type == 'usmNoPrivProtocol' and \
                    auth_pass in valid_auth_type:
                return_value = UsmUserData(user, auth_pass,\
                                   authProtocol=eval(auth_type))
            elif auth_type in valid_auth_type and priv_type in valid_priv_type:
                return_value = UsmUserData(user, auth_pass, priv_pass, \
                                   authProtocol=eval(auth_type),\
                                   privProtocol=eval(priv_type))
            else:
                return_value = UsmUserData(user)
        else:
            t.log(level="DEBUG", message="Invalid Version")
            raise Exception("Invalid Version")
        t.log(level="DEBUG", message="Exiting 'create_community_data' with return value/code :\n"+str(return_value))
        return return_value
示例#21
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()
示例#22
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)
示例#23
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)
示例#24
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'))
示例#25
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
示例#26
0
 def snmp_connect(self):
     error_indication, error_status, error_index, var_binds = next(
         getCmd(
             SnmpEngine(), CommunityData('public'),
             UdpTransportTarget((self.entry.get_ip(), 161),
                                timeout=self.entry.get_timeout(161),
                                retries=1), ContextData(),
             ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
             ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0'))))
     if error_indication:
         result = -1
     elif error_status:
         result = -1
     else:
         result = "OK"
     return result
示例#27
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)
示例#28
0
def set_admin_status(player: int):
    switch = current_app.config['SWITCHES'][player]
    engine = SnmpEngine()
    auth_data = CommunityData(switch['community'], mpModel=1)
    transport = UdpTransportTarget((switch['address'], switch['port']))
    with StateLock:
        desired_state = list(
            zip(switch['interfaces'], current_app.cell_state[player]))
    for chunk in chunked(
        (ObjectType(ObjectIdentity(ifAdminStatus.oid + (if_index, )),
                    Integer32(cell_state.admin_status.value))
         for if_index, cell_state in desired_state), 24):
        cmd = setCmd(engine, auth_data, transport, ContextData(), *chunk)
        errorIndication, errorStatus, errorIndex, varBinds = next(cmd)
        if errorIndication is not None:
            raise Exception("SNMP error returned")
示例#29
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
示例#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)