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
Ejemplo n.º 2
0
def add_row_oids(target, oids_and_values,credentials):
    """
    Send a set SNMP request for row creation (=list) using OIDs
    inputs:
        target (str) : Device IP address
        oids_and_values  list((oid,value)) : List of tuples
            -oid (str)
            -value : Casted value to set ( with respect for rfc1902 type specification )
        credentials (str) : SNMP Community
    outputs:
        SNMP response (dict)
    """
    port=161
    engine=hlapi.SnmpEngine()
    context=hlapi.ContextData()
    ObjectList=list()
    for oid,value in oids_and_values:
        ObjectList.append(ObjectType(ObjectIdentity(oid),value))
    handler = hlapi.setCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *ObjectList
    )
    return fetch(handler)
Ejemplo n.º 3
0
def set_oid_value(oid, value, host="localhost", port=1024):
    """Helper function to set snmp oid value of a device"""
    error_indicator, error_status, error_idx, var_binds = next(
        hlapi.setCmd(
            hlapi.SnmpEngine(),
            hlapi.CommunityData("private", mpModel=0),
            hlapi.UdpTransportTarget((host, port)),
            hlapi.ContextData(),
            hlapi.ObjectType(hlapi.ObjectIdentity(oid), value),
            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
Ejemplo n.º 4
0
def set(oid,
        value,
        host,
        port=161,
        community='private',
        timeout=0,
        retries=0,
        snmp_ver=2):
    try:
        for (err_i, err_st, err_idx, vals) in snmp_engine.setCmd(
                snmp_engine.SnmpEngine(),
                snmp_engine.CommunityData(community, mpModel=snmp_ver - 1),
                snmp_engine.UdpTransportTarget((host, port),
                                               timeout=timeout,
                                               retries=retries),
                snmp_engine.ContextData(),
                snmp_engine.ObjectType(snmp_engine.ObjectIdentity(oid),
                                       value)):
            if err_i or err_st:
                logging.debug('snmp error: %s' % err_i)
                return None
            else:
                return True
    except:
        log_traceback()
        return False
Ejemplo n.º 5
0
    def set(self,
            target,
            value_pairs,
            community,
            port=161,
            version=1,
            timeout=1,
            retries=3,
            engine=hlapi.SnmpEngine(),
            context=hlapi.ContextData()):
        try:
            handler = hlapi.setCmd(
                engine, hlapi.CommunityData(community, mpModel=version),
                hlapi.UdpTransportTarget((target, port),
                                         timeout=timeout,
                                         retries=retries), context,
                *self._construct_value_pairs(value_pairs))
        except Exception as 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
Ejemplo n.º 6
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)
Ejemplo n.º 7
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 "?",
            ))
Ejemplo n.º 8
0
    def set(self, oid, value):
        """Use PySNMP to perform an SNMP SET operation on a single object.

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

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

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

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

        if error_status:
            # SNMP PDU error.
            raise exception.SNMPFailure(operation="SET",
                                        error=error_status.prettyPrint())
Ejemplo n.º 9
0
def set(target, value_pairs, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()):
    handler = hlapi.setCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *construct_value_pairs(value_pairs)
    )
    return fetch(handler, 1)[0]
Ejemplo n.º 10
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 '?'))
Ejemplo n.º 11
0
 def set(self, oid, value):
     identify = hlapi.ObjectType(hlapi.ObjectIdentity(oid),
                                 hlapi.Integer(value))
     g = hlapi.setCmd(self.engine,
                      self.community,
                      self.transport,
                      self.context,
                      identify,
                      lookupMib=False)
     next(g)
Ejemplo n.º 12
0
def set_one(target,
            oid,
            value,
            credentials,
            port=161,
            engine=hlapi.SnmpEngine(),
            context=hlapi.ContextData()):
    handler = hlapi.setCmd(engine, credentials,
                           hlapi.UdpTransportTarget((target, port)), context,
                           hlapi.ObjectType(hlapi.ObjectIdentity(oid), value))
    return fetch(handler, 1)[0]
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
    def port_interaction(self, command, port_number):
        if command == "on":
            set_bit = self.onsetting
        elif command == "off":
            set_bit = self.offsetting
        else:
            raise UnknownCommandException("Unknown command %s." % (command))

        transport = UdpTransportTarget((self.hostname, 161))
        objecttype = ObjectType(
            ObjectIdentity(self.mib, self.controlpoint,
                           port_number).addAsn1MibSource(
                               'http://mibs.snmplabs.com/asn1/@mib@'),
            int(set_bit))

        if self.version == 'snmpv3':
            if not self.username:
                raise FailedRequestException("No username set for snmpv3")
            userdata = UsmUserData(self.username, self.authpass, self.privpass)
            errorIndication, errorStatus, errorIndex, varBinds = next(
                setCmd(SnmpEngine(), userdata, transport, ContextData(),
                       objecttype))
        elif self.version == 'snmpv1':
            if not self.community:
                raise FailedRequestException("No community set for snmpv1")
            errorIndication, errorStatus, errorIndex, varBinds = next(
                setCmd(SnmpEngine(), CommunityData(self.community), transport,
                       ContextData(), objecttype))
        else:
            raise FailedRequestException("Unknown snmp version")

        if errorIndication:
            raise FailedRequestException(errorIndication)
        elif errorStatus:
            raise FailedRequestException(errorStatus)
        else:
            for varBind in varBinds:
                log.debug(' = '.join([x.prettyPrint() for x in varBind]))
            return True
Ejemplo n.º 15
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)
Ejemplo n.º 16
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")
Ejemplo n.º 17
0
def polatis_oxc(port, oxc):
    """ Use SNMP to run cross-connects on a Polatis optical switch.
    To delete a cross-connect set oxc to 0.

    Example: polatis_oxc(2,194) connects Ingress port 2 with Egress port 194
    """
    # logger.warn('Polatis SNMP cross-connect {},{}'.format(port, oxc))
    polatis = 'mts01sqsccc.spoc.charterlab.com'
    oid = '1.3.6.1.4.1.26592.2.2.2.1.2.1.2.{}'
    g = setCmd(
        SnmpEngine(),
        CommunityData('private'),
        UdpTransportTarget((polatis, 161)),
        ContextData(),
        ObjectType(
            # First Port
            ObjectIdentity(oid.format(port)),
            # Second Port
            Unsigned32(oxc)))
    next(g)
Ejemplo n.º 18
0
def set_SNMP_value(community, ip, MIB, obj, oid, value):
    """ Performs an SNMP RW request and sets the given oid to the given value """
    errorIndication, errorStatus, errorIndex, varBinds = next(
        setCmd(SnmpEngine(),
               CommunityData(community),
               UdpTransportTarget((ip, 161)),
               ContextData(),
               ObjectType(ObjectIdentity(MIB, obj, oid))
               ))
    if errorIndication:
        raise NetworkManagerReadError("SNMP read error:" + str(errorIndication))
    elif errorStatus:
        raise NetworkManagerReadError('SNMP read error: %s at %s' % (errorStatus.prettyPrint(),
                                                                     errorIndex and varBinds[int(errorIndex) - 1][
                                                                         0] or '?'))
    else:
        if len(varBinds) > 1:
            raise NetworkManagerReadError("SNMP read error: too many values in response")

        return varBinds[0][1].prettyPrint()
Ejemplo n.º 19
0
def snmp_set(paramaters):
    connection_paramaters = paramaters['connection']
    oid = paramaters['oid']
    value = paramaters['value']

    logging.debug('iputils: SNMP set OID "{0}" on "{1}" to "{2}"...'.format(
        oid, connection_paramaters['host'], value))

    cmd = hlapi.setCmd(*_snmp_connection(connection_paramaters),
                       hlapi.ObjectType(hlapi.ObjectIdentity(oid), value))

    error, errorStatus, errorIndex, result = next(cmd)
    if error is not None:
        raise Exception(
            'Error with SNMP Set: "{0}", Error Status: "{1}", Error Index: {2}'
            .format(error, errorStatus, errorIndex))

    logging.info('iputils: SNMP set OID "{0}" on "{1}" to "{2}"'.format(
        oid, connection_paramaters['host'], value))

    return {'done': True}
Ejemplo n.º 20
0
 def outlet_ramp_delay(self, set_delay=None):
     '''The number of seconds to delay before powering on the given outlet:
         integer values only
     '''
     if set_delay is None:
         # Get current outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampDelay',
                                         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, 'tlpPduOutletRampDelay',
                                         self.device_id, self.outlet_id)
         g = setCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(), rfc1902.ObjectType(obj_id),
                    int(set_delay))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
Ejemplo n.º 21
0
    def _oid_set(self, oid, value):
        """
        Performs set command to specific OID with a given value by sending a SNMP Set message.

        Args:
            oid (str): Full OID identifying the object to be read.
            value (int): Value to be written to the OID as Integer32.
        """
        errorIndication, errorStatus, errorIndex, varBinds = next(
            setCmd(self._snmp_engine, self._community_data,
                   self._udp_transport_target, self._context,
                   ObjectType(ObjectIdentity(oid), Integer32(value))))

        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)
Ejemplo n.º 22
0
    def change_value(self, req, oid, value):

        try:
            errorIndication, errorStatus, errorIndex, varBinds = next(
                setCmd(
                    SnmpEngine(), CommunityData(self.secret),
                    UdpTransportTarget((self.server, self.port)),
                    ContextData(),
                    ObjectType(ObjectIdentity(req + str(oid)),
                               Integer(value))), )
        except Exception:
            raise
        else:
            if errorIndication:
                return SNMPError(errorIndication)
            elif errorStatus:
                return SNMPError(errorStatus)
            else:
                if len(varBinds) == 1:
                    return varBinds[0][1]
                else:
                    raise SNMPError("Multiple MIB variables returned.")
Ejemplo n.º 23
0
def set_oid(target, oids, credentials,data):
    """
    Send a set SNMP request for a single OID
    inputs:
        target (str) : Device IP address
        oids (str) : Single OID to set
        credentials (str) : SNMP Community
        data : Value to set. Must be casted according to rfc1902 OID type specification before calling
    outputs:
        SNMP response (dict)
    """
    port=161
    engine=hlapi.SnmpEngine()
    context=hlapi.ContextData()
    handler = hlapi.setCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        ObjectType(ObjectIdentity(oids),data)
    )
    return fetch(handler)
Ejemplo n.º 24
0
Archivo: snmp.py Proyecto: alttch/eva3
def set(oid,
        value,
        host,
        port=161,
        community='private',
        timeout=0,
        retries=0,
        snmp_ver=2):
    """
    Args:
        oid: SNMP OID or MIB name
        value: value to set
        host: target host
        port: target port (default: 161)
        community: SNMP community (default: public)
        timeout: max SNMP timeout
        retries: max retry count (default: 0)
        snmp_ver: SNMP version (default: 2)

    Returns:
        True if value is set, False if not
    """
    try:
        for (err_i, err_st, err_idx, vals) in snmp_engine.setCmd(
                snmp_engine.SnmpEngine(),
                snmp_engine.CommunityData(community, mpModel=snmp_ver - 1),
                snmp_engine.UdpTransportTarget(
                    (host, port), timeout=timeout, retries=retries),
                snmp_engine.ContextData(),
                snmp_engine.ObjectType(snmp_engine.ObjectIdentity(oid), value)):
            if err_i or err_st:
                logging.debug('snmp error: %s' % err_i)
                return None
            else:
                return True
    except:
        log_traceback()
        return False
Ejemplo n.º 25
0
 def outlet_ramp_action(self, set_action=None):
     '''The ramp action to take on a given outlet when powering on the 
     device:
         0 = remain off
         1 = turn on after delay
     '''
     if set_action is None:
         # Get current outlet state
         obj_id = rfc1902.ObjectIdentity(self.mib, 'tlpPduOutletRampAction',
                                         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, 'tlpPduOutletRampAction',
                                         self.device_id, self.outlet_id)
         g = setCmd(SnmpEngine(), self.community, self.transport_target,
                    ContextData(),
                    rfc1902.ObjectType(obj_id, int(set_action)))
         errorIndication, errorStatus, errorIndex, varBinds = next(g)
Ejemplo n.º 26
0
def add_row(target, oids_and_values,credentials):
    """
    Send a set SNMP request for row creation (=list) using MIB
    inputs:
        target (str) : Device IP address
        oids_and_values  list(MIB entry) : List of MIB entries (as tuples, see pyconfig.py for examples)
        credentials (str) : SNMP Community
    outputs:
        SNMP response (dict)
    """
    port=161
    engine=hlapi.SnmpEngine()
    context=hlapi.ContextData()
    ObjectList=list()
    handler = hlapi.setCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *construct_object_types_from_name_set(oids_and_values)
    )
    print(handler)
    return fetch(handler)
Ejemplo n.º 27
0
def snmp_set(target,
             value_pairs,
             communityname,
             port=161,
             engine=hlapi.SnmpEngine(),
             context=hlapi.ContextData()):
    """
    Constuctor function for setting OID data to device. Values set are returned back.

    @params:
        target            - Required  : IP address of the device (Str)
        value_pairs       - Required  : Dictionary of OIDs and values, where OID is the key. (Dict)
        communityname     - Required  : SNMP community name (Str)
        port              - Optional  : UDP port for SNMP request (Int)
        engine            - Optional  : SNMP engine for request, from pysnmp hlapi (Obj)
        context           - Optional  : SNMP context data for request, from pysnmp hlapi (Obj)

    @return:
        fetch()           : Dictionary of OID values from fetch function.
    """
    handler = hlapi.setCmd(engine, communityname,
                           hlapi.UdpTransportTarget((target, port)), context,
                           *construct_value_pairs(value_pairs))
    return fetch(handler, 1)
Ejemplo n.º 28
0
    def snmpSet(self,
                value_pairs,
                credentials='',
                port=161,
                engine=hlapi.SnmpEngine(),
                context=hlapi.ContextData()):
        target = self.__dut_ip

        if self.__snmp_ver.lower() == '2c':
            credentials = hlapi.CommunityData('private')

        handler = hlapi.setCmd(engine, credentials,
                               hlapi.UdpTransportTarget((target, port)),
                               context, *construct_value_pairs(value_pairs))

        ret = fetch(handler, 1)[0]
        ret_list = []

        for key, value in ret.items():
            temp = key + ': ' + value
            ret_list.append(temp)

        UI.log('SNMP-SET', 'Remote IP: ' + self.__dut_ip, *ret_list)
        return ret
Ejemplo n.º 29
0
    def _set(self, *key_vals):
        """Set variable via SNMP

        Args:
            variable : variable to set via SNMP.
            value    : value to set on the given variable.

        """
        if (self.dry):
            # Convert to the corresponding net-snmp command
            for key, val in key_vals:
                # SNMP OID
                if (isinstance(key, tuple)):
                    key = ".".join([str(x) for x in key])
                else:
                    key += ".0"  # scalar values must have a .0 suffix
                # Translate values
                # TODO: Fix s400LOFrequency.0, which is not writable due to
                # being a Counter64 object.
                if ("s400ModulationStandard" in key):
                    if (val in standard_snmp_table):
                        val = standard_snmp_table[val]
                if ("s400Modcod" in key):
                    if (val in modcod_snmp_table):
                        val = modcod_snmp_table[val]
                if ("RowStatus" in key):
                    if (val in snmp_row_status_table):
                        val = snmp_row_status_table[val]
                if (val in ["disable", "enable"]):
                    val = int(val == "enable")
                if (val in ["disabled", "enabled"]):
                    val = int(val == "enabled")
                if (val in ["vertical", "horizontal"]):
                    val = int(val == "horizontal")
                # Value type
                if isinstance(val, str):
                    val_type = "s"
                elif (("LBandFrequency" in key)
                      or ("SymbolRate" in key and "SymbolRateAuto" not in key)
                      or ("s400MpePid1Pid" in key)):
                    val_type = "u"
                else:
                    val_type = "i"
                print("> snmpset -v 2c -c private {}:{} {}::{} {} {}".format(
                    self.address, self.port, self.mib, key, val_type, val))
            return

        obj_types = []
        for key, val in key_vals:
            if isinstance(key, tuple):
                obj = ObjectType(
                    ObjectIdentity(self.mib, key[0],
                                   key[1]).addMibSource(self.mib_dir), val)
            else:
                obj = ObjectType(
                    ObjectIdentity(self.mib, key,
                                   0).addMibSource(self.mib_dir), val)
            obj_types.append(obj)

        errorIndication, errorStatus, errorIndex, varBinds = next(
            setCmd(self.engine, CommunityData('private'),
                   UdpTransportTarget((self.address, self.port), timeout=10.0),
                   ContextData(), *obj_types))

        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(' = '.join([x.prettyPrint() for x in varBind]))
from pysnmp.hlapi import setCmd, SnmpEngine, CommunityData
from pysnmp.hlapi import UdpTransportTarget, ContextData, ObjectType
from pysnmp.hlapi import  ObjectIdentity, OctetString
import credentials2 as cred

# MibVariable
oid = ObjectIdentity('SNMPv2-MIB', 'sysName', 0)

target_addr = (cred.ip, cred.snmp_port)

snmp_engine_obj = SnmpEngine()
com_data_obj = CommunityData(cred.community_string)
udp_transport_target_obj = UdpTransportTarget(target_addr)
context_data_obj = ContextData()
# otype_oid = ObjectType(oid, OctetString("New description"))
otype_oid = ObjectType(oid, "New system name")

gen = setCmd(snmp_engine_obj, com_data_obj,
              udp_transport_target_obj,
              context_data_obj,
              otype_oid,
              lookupNames=False, lookupValues=True)

*errorInformation, varBinds = next(gen)
# errorIndication, errorStatus, errorIndex = errorInformation
# print(errorInformation)  # [None, 0, 0]

for rfc1902obj in varBinds:
    print(rfc1902obj.prettyPrint())