示例#1
0
    def send_trap(self):
        """ Send a SNMP trap with id `trapid` to the IP address `manager`
        """
        oid = self.options.eoid             # cascade enterprise Object ID
        trapid = self.options.trapid        # base string for trap indicators

        community = self.options.community
        manager_ip = self.options.manager_ip

        severity = self.options.severity
        description = self.trap_description
        url = self.options.trap_url
        alert_level = self.options.alert_level
        now = timeutils.datetime_to_seconds(datetime.datetime.now())

        trapname = '.'.join([oid, trapid])

        ntf = ntforg.NotificationOriginator()

        err = ntf.sendNotification(ntforg.CommunityData(community),
                                   ntforg.UdpTransportTarget((manager_ip, 162)),
                                   'trap',
                                   trapname, 
                                   ('1.3.6.1.2.1.1.3.0', rfc1902.Integer(0)),                         # Uptime
                                   ('1.3.6.1.4.1.7054.71.2.1.0', rfc1902.Integer(severity)),            # Severity
                                   ('1.3.6.1.4.1.7054.71.2.3.0', rfc1902.OctetString(description)),
                                   ('1.3.6.1.4.1.7054.71.2.4.0', rfc1902.Integer(0)),                   # Event ID
                                   ('1.3.6.1.4.1.7054.71.2.5.0', rfc1902.OctetString(url)),
                                   ('1.3.6.1.4.1.7054.71.2.7.0', rfc1902.Integer(alert_level)),         # Alert Level
                                   ('1.3.6.1.4.1.7054.71.2.8.0', rfc1902.Integer(now)),                 # Start Time
                                   ('1.3.6.1.4.1.7054.71.2.16.0', rfc1902.Integer(0)),                  # Source Count
                                   ('1.3.6.1.4.1.7054.71.2.18.0', rfc1902.Integer(0)),                  # Destination Count
                                   ('1.3.6.1.4.1.7054.71.2.20.0', rfc1902.Integer(0)),                  # Protocol Count
                                   ('1.3.6.1.4.1.7054.71.2.22.0', rfc1902.Integer(0)),                  # Port Count                                
                                   )
示例#2
0
文件: linksys.py 项目: sohonet/HEN
    def __createVLAN(self, vlan_id, vlan_name):
        """\brief Creates a vlan given an id
        \param vlan_id (\c int) vlan id to add
        \return (\int) 0 if the operation is successful, -1 if it failed.
        """
        log.debug(str(OID.dot1qVlanStaticRowStatus + (vlan_id, )))
        # you create a vlan using its tagged id
        snmp_list = []
        snmp_list.append((OID.dot1qVlanStaticName + (vlan_id, ),
                          rfc1902.OctetString(str(vlan_name))))
        snmp_list.append((OID.dot1qVlanStaticEgressPorts + (vlan_id, ),
                          rfc1902.OctetString(self.getEmptyBitMap(64))))
        snmp_list.append((OID.dot1qVlanForbiddenEgressPorts + (vlan_id, ),
                          rfc1902.OctetString(self.getEmptyBitMap(64))))
        snmp_list.append((OID.dot1qVlanStaticUntaggedPorts + (vlan_id, ),
                          rfc1902.OctetString(self.getEmptyBitMap(64))))
        snmp_list.append(
            (OID.dot1qVlanStaticRowStatus + (vlan_id, ), rfc1902.Integer32(4)))

        self.snmp.complex_set(snmp_list)

        if self.snmp.getErrorStatus():
            log.debug("Error creating vlan with id " + str(vlan_id) +
                      " on switch " + str(self.getSwitchName()))
            return -1
        return 0
示例#3
0
文件: config.py 项目: rsmetana/Python
def addVacmView(snmpEngine, viewName, viewType, subTree, subTreeMask):
    vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(
        snmpEngine, viewName, subTree)

    # Allow bitmask specification in form of an OID
    if rfc1902.OctetString('.').asOctets() in rfc1902.OctetString(subTreeMask):
        subTreeMask = rfc1902.ObjectIdentifier(subTreeMask)

    if isinstance(subTreeMask, rfc1902.ObjectIdentifier):
        subTreeMask = tuple(subTreeMask)
        if len(subTreeMask) < len(subTree):
            subTreeMask += (1,) * (len(subTree) - len(subTreeMask))

        subTreeMask = rfc1902.OctetString.fromBinaryString(
            ''.join(str(x) for x in subTreeMask))

    snmpEngine.msgAndPduDsp.mibInstrumController.writeVars(
        ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),)
    )

    snmpEngine.msgAndPduDsp.mibInstrumController.writeVars(
        ((vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName),
         (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree),
         (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, subTreeMask),
         (vacmViewTreeFamilyEntry.name + (4,) + tblIdx, viewType),
         (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo'))
    )
示例#4
0
    def test_sendTrap(self, mock_ntforg, mock_snmp_config):

        self.mock_queue = mock.MagicMock

        with mock.patch(
                'bdssnmpadaptor.config.open',
                side_effect=[io.StringIO(self.CONFIG),
                             io.StringIO(self.CONFIG),
                             io.StringIO(self.CONFIG)]):
            ntf = snmp_notificator.SnmpNotificationOriginator(
                mock.MagicMock(config={}), self.mock_queue)

        self.my_loop.run_until_complete(ntf.sendTrap({}))

        mock_snmpEngine = mock_snmp_config.getSnmpEngine.return_value

        expectedVarBinds = [
            (rfc1902.ObjectIdentifier('1.3.6.1.2.1.1.3.0'), mock.ANY),
            (rfc1902.ObjectIdentifier('1.3.6.1.6.3.1.1.4.1.0'), rfc1902.ObjectIdentifier('1.3.6.1.4.1.50058.103.1.0.1.1')),
            (rfc1902.ObjectIdentifier('1.3.6.1.4.1.50058.104.2.1.1.0'), rfc1902.Integer32(1)),
            (rfc1902.ObjectIdentifier('1.3.6.1.4.1.50058.104.2.1.2.0'), rfc1902.OctetString('error')),
            (rfc1902.ObjectIdentifier('1.3.6.1.4.1.50058.104.2.1.3.0'), rfc1902.Integer32(0)),
            (rfc1902.ObjectIdentifier('1.3.6.1.4.1.50058.104.2.1.4.0'), rfc1902.OctetString('error')),
        ]

        ntf._ntfOrg.sendVarBinds.assert_called_once_with(
            mock_snmpEngine, mock.ANY, None, '', expectedVarBinds, mock.ANY)
示例#5
0
    def setup_snmp_trap(self, alert):
        oid = self.eoid  # cascade enterprise Object ID
        trapid = self.trapid  # base string for trap indicators
        self.trapname = '.'.join([oid, trapid])

        severity = self.severity
        description = alert.message or self.default_description
        alert_level = AlertLevels.get_integer(self.level)
        now = timeutils.datetime_to_seconds(alert.timestamp)

        self.binds = (
            ('1.3.6.1.2.1.1.3.0', rfc1902.Integer(0)),  # Uptime
            ('1.3.6.1.4.1.7054.71.2.1.0',
             rfc1902.Integer(severity)),  # Severity
            ('1.3.6.1.4.1.7054.71.2.3.0', rfc1902.OctetString(description)),
            ('1.3.6.1.4.1.7054.71.2.4.0', rfc1902.Integer(0)),  # Event ID
            ('1.3.6.1.4.1.7054.71.2.5.0', rfc1902.OctetString(self.trap_url)),
            ('1.3.6.1.4.1.7054.71.2.7.0',
             rfc1902.Integer(alert_level)),  # Alert Level
            ('1.3.6.1.4.1.7054.71.2.8.0', rfc1902.Integer(now)),  # Start Time
            ('1.3.6.1.4.1.7054.71.2.16.0', rfc1902.Integer(0)),  # Source Count
            ('1.3.6.1.4.1.7054.71.2.18.0',
             rfc1902.Integer(0)),  # Destination Count
            ('1.3.6.1.4.1.7054.71.2.20.0',
             rfc1902.Integer(0)),  # Protocol Count
            ('1.3.6.1.4.1.7054.71.2.22.0', rfc1902.Integer(0)),  # Port Count
        )
示例#6
0
    def check_power(self, ipmi_server, node_id):
        power_states = self.client.get_power_state(ipmi_server)

        cluster_name = self._cfg.clusters[0].name
        node_name = cluster_name + '-' + str(node_id + 1)

        # notify on every failed PS we find and set notified state to True
        try:
            for PS in power_states['FAIL']:
                if not self.notified_power_supply_failure[node_id][PS]:
                    message = PS + " in " + node_name + " failed"
                    subject = "[ALERT] Qumulo Power Supply Failure " + node_name
                    self.notify(subject,
                                message,
                                "powerSupplyFailureTrap",
                                [(rfc1902.ObjectName('1.3.6.1.4.1.47017.8'),
                                  rfc1902.OctetString(node_name)),
                                 (rfc1902.ObjectName('1.3.6.1.4.1.47017.11'),
                                  rfc1902.OctetString(PS))
                                 ]
                                )
                    self.notified_power_supply_failure[node_id][PS] = True
        except TypeError, err:
            self.logger.warn("WARNING: IPMI Exception, please verify IPMI config. (%s)"
                     % str(err))
示例#7
0
    def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU,
                            acInfo):
        trunkReq = gCurrentRequestContext['request']

        logMsg = '(SNMP request %s), matched keys: %s' % (', '.join([
            x == 'snmp-pdu' and 'snmp-var-binds=%s' %
            prettyVarBinds(trunkReq['snmp-pdu']) or '%s=%s' %
            (x, isinstance(trunkReq[x], int) and trunkReq[x]
             or rfc1902.OctetString(trunkReq[x]).prettyPrint())
            for x in trunkReq
        ]), ', '.join([
            '%s=%s' % (k, gCurrentRequestContext[k])
            for k in gCurrentRequestContext if k[-2:] == 'id'
        ]))

        usedPlugins = []
        pluginIdList = gCurrentRequestContext['plugins-list']
        snmpReqInfo = gCurrentRequestContext['request'].copy()
        for pluginId in pluginIdList:
            usedPlugins.append((pluginId, snmpReqInfo))

            st, PDU = pluginManager.processCommandRequest(
                pluginId, snmpEngine, PDU, **snmpReqInfo)
            if st == status.BREAK:
                break
            elif st == status.DROP:
                log.msg('plugin %s muted request %s' % (pluginId, logMsg))
                self.releaseStateInformation(stateReference)
                return
            elif st == status.RESPOND:
                log.msg('plugin %s forced immediate response %s' %
                        (pluginId, logMsg))
                self.sendPdu(snmpEngine, stateReference, PDU)
                self.releaseStateInformation(stateReference)
                return

        # pass query to trunk

        trunkReq['snmp-pdu'] = PDU
        trunkIdList = gCurrentRequestContext['trunk-id-list']
        if trunkIdList is None:
            log.msg('no route configured %s' % logMsg)
            self.releaseStateInformation(stateReference)
            return

        for trunkId in trunkIdList:
            log.msg('received SNMP message (%s), sending through trunk %s' %
                    (', '.join([
                        x == 'snmp-pdu' and 'snmp-var-binds=%s' %
                        prettyVarBinds(trunkReq['snmp-pdu']) or '%s=%s' %
                        (x, isinstance(trunkReq[x], int) and trunkReq[x]
                         or rfc1902.OctetString(trunkReq[x]).prettyPrint())
                        for x in trunkReq
                    ]), trunkId))

            cbCtx = usedPlugins, trunkId, trunkReq, snmpEngine, stateReference

            trunkingManager.sendReq(trunkId, trunkReq, self.__recvCb, cbCtx)
示例#8
0
def Snmp(action=None,
         target_IP=None,
         community='public',
         oid=None,
         stype=None,
         value=None,
         walk_timeout=120):
    """
    Name:Snmp
    Purpose: Do snmp set,get and walk function for DUT control.
    Input:1.action
    	    2.target_IP
         3.community
         4.oid
         5.stype
         6.value
         7.walk_timeout
    Output:Snmp get or walk result
    """

    # Create command generator
    cmdGen = cmdgen.CommandGenerator()

    if action == "get":
        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            cmdgen.CommunityData(community),
            cmdgen.UdpTransportTarget((target_IP, 161), timeout=1, retries=3),
            oid)
        for name, val in varBinds:
            if val.prettyPrint() != "":
                return val.prettyPrint()
            else:
                return "null"
    elif action == "set":
        for case in switch(stype):
            if case('i'):
                value = rfc1902.Integer(value)
                break
            elif case('s'):
                value = rfc1902.OctetString(value)
                break
            elif case('x'):
                value = rfc1902.OctetString(hexValue=value)
                break
            elif case('p'):
                value = rfc1902.IpAddress(value)
            elif case('u'):
                value = rfc1902.Unsigned32(value)
                break
            elif case():  # default
                value = ""

        cmdGen.setCmd(
            cmdgen.CommunityData(community),
            cmdgen.UdpTransportTarget((target_IP, 161), timeout=1, retries=3),
            (oid, value))
示例#9
0
    def setup_snmp_trap(self, alert):
        oid = self.eoid  # cascade enterprise Object ID
        trapid = self.trapid  # base string for trap indicators
        self.trapname = '.'.join([oid, trapid])

        context = urllib.urlencode(alert.event.trigger_result)
        eid = alert.event.eventid

        self.binds = (
            # eventID == UUID
            ('1.3.6.1.4.1.17163.1.500.1.1.1', rfc1902.OctetString(eid)),

            # eventContext
            ('1.3.6.1.4.1.17163.1.500.1.1.4', rfc1902.OctetString(context)),
        )
示例#10
0
文件: linksys.py 项目: sohonet/HEN
    def __setPortList(self, pl, internal_port, enable):
        #log.debug("internal_port "+str(internal_port)+" enabled "+str(enable))
        #log.debug("start "+str(self.printPortMap(pl,enable)) )
        raw_ports = array('B')
        for i in range(0, len(pl)):
            raw_ports.extend(unpack('B', pl[i]))

        port_number = 0

        for i in range(0, len(raw_ports)):
            for slot in range(0, 8):
                port_number = port_number + 1
                if (port_number == int(internal_port)):
                    if enable:
                        #log.debug("setting port "+str(i)+" " +str(slot)+" to on")
                        raw_ports[i] = (raw_ports[i] | Switch.mask[slot])
                    else:
                        #log.debug("setting port "+str(i)+" " +str(slot)+" to off")
                        raw_ports[i] = (raw_ports[i] & Switch.inv_mask[slot])
        s = ""
        for i in range(0, len(raw_ports)):
            s = s + pack('B', raw_ports[i])

        #log.debug( "end   "+str(self.printPortMap(s,enable)) )
        return rfc1902.OctetString(s)
示例#11
0
文件: switch.py 项目: sohonet/HEN
 def setSwitchContact(self,s):
     """\brief Retrieves the switch's contact
     \param s (\c string) The switch's contact
     \return (\c int) Returns 0 if successful, -1 if unsuccessful
     """
     self.snmp.set(OID.sysContact,rfc1902.OctetString(s))
     return self.snmp.getErrorStatus()
示例#12
0
def set_snmp_single(rwstring, ip_address, ifAlias, description):
    from pysnmp.entity.rfc3413.oneliner import cmdgen
    from pysnmp.proto import rfc1902
    cmdGen = cmdgen.CommandGenerator()
    cmdGen.setCmd(cmdgen.CommunityData(rwstring),
                  cmdgen.UdpTransportTarget((ip_address, 161)),
                  (ifAlias, rfc1902.OctetString(description)))
示例#13
0
文件: switch.py 项目: sohonet/HEN
 def setSwitchLocation(self,s):
     """\brief Retrieves the switch's location
     \param s (\c string) The switch's location
     \return (\c int) Returns 0 if successful, -1 if unsuccessful
     """
     self.snmp.set(OID.sysLocation,rfc1902.OctetString(s))
     return self.snmp.getErrorStatus()
示例#14
0
文件: SET.py 项目: analylx/learn
def snmpv2_set(ip, community, oid, value, port=161):
    cmdGen = cmdgen.CommandGenerator()
    # print(dir(rfc1902))
    # 类型 ['ApplicationSyntax', 'Bits', 'Counter32', 'Counter64', 'Gauge32', 'Integer', 'Integer32', 'IpAddress', 'ObjectIdentifier', 'ObjectName', 'ObjectSyntax', 'OctetString', 'Opaque', 'SimpleSyntax', 'TimeTicks', 'Unsigned32', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'constraint', 'error', 'namedtype', 'namedval', 'rfc1155', 'tag', 'univ', 'version_info']
    # 需要提前通过OIDVIEW查询类型
    # 通过不同的类型写入数据
    if isinstance(value, str):
        set_value = rfc1902.OctetString(value)
    elif isinstance(value, int):
        set_value = rfc1902.Integer(value)

    errorIndication, errorStatus, errorindex, varBinds = cmdGen.setCmd(
        cmdgen.CommunityData(community),  # 写入Community
        cmdgen.UdpTransportTarget((ip, port)),  # IP地址和端口号
        (oid, set_value)  # OID和写入的内容,需要进行编码!
    )
    # 错误处理
    if errorIndication:
        print("写入错误!!!")
        print(errorIndication)
    elif errorStatus:
        print("写入错误!!!")
        print('%s at %s' %
              (errorStatus.prettyPrint(),
               errorindex and varBinds[int(errorindex) - 1][0] or '?'))
    else:
        print("写入成功!!!")
    # 打印回显示结果
    for name, val in varBinds:
        print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))  # 打印修改的结果
示例#15
0
文件: linksys.py 项目: sohonet/HEN
    def __getVLANInternalID(self, vlanName):
        """\brief Retrieves a vlan's internal id given its name. The function returns
                  the following codes:
                  -1: if the vlan does not exist on the switch
                   0: if successful
        \param vlanName (\c string) The name of the vlan
        \return (\c string) The internal id of the vlan if found, negative otherwise
        """
        ## Optimisation could be done here to ensure lookups are faster.
        ## Use a dictionary of id to name.

        internalID = None

        # no default vlan in the snmp tables for the linksys
        if (vlanName == "Default VLAN"):
            return "1"

        dot1qVlanStaticNameTable = self.getDot1qVlanStaticName()
        for dot1qVlanStaticNameTableRow in dot1qVlanStaticNameTable:
            if dot1qVlanStaticNameTableRow[0][1] == rfc1902.OctetString(
                    vlanName):
                internalID = dot1qVlanStaticNameTableRow[0][0][
                    len(dot1qVlanStaticNameTableRow[0][0]) - 1]

        if (internalID == None):
            return -1

        return internalID
示例#16
0
 def _set_port_untagged_status(self, port, status):
     previous_untagged_vlan = port.untagged_vlan
     if status == True:
         # To add a port to a VLAN untagged, it first needs to be added as tagged
         self.add_tagged_port(port)
     # Add the port to the list of untagged ports for this VLAN
     dot1qVlanStaticUntaggedPorts = self.switch.snmp_get(
         ("dot1qVlanStaticUntaggedPorts", self.vid))
     new_untagged_port_list = VLAN._set_port_list_port_status(
         dot1qVlanStaticUntaggedPorts, port, status)
     if dot1qVlanStaticUntaggedPorts != new_untagged_port_list:
         self.switch.snmp_set((("dot1qVlanStaticUntaggedPorts", self.vid),
                               rfc1902.OctetString(new_untagged_port_list)))
     # Only set the pvid if the port is being added to the VLAN
     if status == True:
         dot1qPvid = self.switch.snmp_get(("dot1qPvid", port.base_port))
         if dot1qPvid != self.vid:
             self.switch.snmp_set(
                 (("dot1qPvid", port.base_port), rfc1902.Gauge32(self.vid)))
         # Remove the port from the VLAN that it belonged to before
         if previous_untagged_vlan is not None and self != previous_untagged_vlan:
             previous_untagged_vlan.remove_untagged_port(port)
     # If the port was just removed from dot1qVlanStaticUntaggedPorts, it is still in dot1qVlanStaticEgressPorts and
     # therefore still egresses this VLAN tagged
     if status == False:
         self.remove_tagged_port(port)
示例#17
0
    def createVLAN(self, vlan):
        vlanName = vlan.getName()
        vlanNames = self.getVLANNames()
        for name in vlanNames.values():
            if (str(name) == str(vlanName)):
                return -1

        self.snmp.set(OID.netgearVlanStaticRowStatus + (vlan.getID(), ),
                      rfc1902.Integer32(5))
        if self.snmp.getErrorStatus():
            print "Error with creating vlan row"
            print self.snmp
            return -2

        self.snmp.set(OID.netgearVlanStaticName + (vlan.getID(), ),
                      rfc1902.OctetString(vlan.getName()))

        if self.snmp.getErrorStatus():
            print "Error with setting vlan name"
            print self.snmp
            return -3
        # Now add the ports to the vlan
        if (self.addPorts(vlan.getName(),
                          vlan.getPortsOnSwitch(self.getSwitchName())) < 0):
            return -4

        return 0
示例#18
0
 def _set_name(self, value):
     # Make sure that the name is legal according to the allowed VLAN names detailed in section 1-40 of the HP
     # Advanced Traffic Management Guide
     assert (all(
         map(lambda illegal_char: illegal_char not in value, "\"\'@#$^&*")))
     self.switch.snmp_set(
         (("dot1qVlanStaticName", self.vid), rfc1902.OctetString(value)))
示例#19
0
 def _op(self, cmd, *oids):
     """Apply an SNMP operation"""
     kwargs = {}
     if self._contextname:
         kwargs['contextName'] = rfc1902.OctetString(self._contextname)
     errorIndication, errorStatus, errorIndex, varBinds = cmd(
         self._auth, self._transport, *oids, **kwargs)
     if errorIndication:
         self._check_exception(errorIndication)
         raise SNMPException(str(errorIndication))
     if errorStatus:
         # We try to find a builtin exception with the same message
         exc = str(errorStatus.prettyPrint())
         exc = re.sub(r'\W+', '', exc)
         exc = "SNMP{0}".format(exc[0].upper() + exc[1:])
         if str(exc) in globals():
             raise globals()[exc]
         raise SNMPException(errorStatus.prettyPrint())
     if cmd in [self._cmdgen.getCmd, self._cmdgen.setCmd]:
         results = [(tuple(name), val) for name, val in varBinds]
     else:
         results = [(tuple(name), val)
                    for row in varBinds for name, val in row]
         if len(results) > 0 and isinstance(results[-1][1],
                                            rfc1905.EndOfMibView):
             results = results[:-1]
     if len(results) == 0:
         if cmd not in [self._cmdgen.nextCmd, self._cmdgen.bulkCmd]:
             raise SNMPException("empty answer")
     return tuple([(oid, self._convert(val)) for oid, val in results])
示例#20
0
    def __coerce_value(initial_value, new_value):
        """Coerce the new_value to the same type as the initial_value.

        :param initial_value: initial value from the device
        :param new_value: new value to set, coerced into the right type
        :return: new value, coerced into the right type
        """
        # pylint: disable=redefined-variable-type
        # In order to return the right type the return value has to be
        # redefined.

        # Types from RFC-1902
        if isinstance(initial_value, rfc1902.Counter32):
            set_value = rfc1902.Counter32(str(new_value))
        elif isinstance(initial_value, rfc1902.Counter64):
            set_value = rfc1902.Counter64(str(new_value))
        elif isinstance(initial_value, rfc1902.Gauge32):
            set_value = rfc1902.Gauge32(str(new_value))
        elif isinstance(initial_value, rfc1902.Integer):
            set_value = rfc1902.Integer(str(new_value))
        elif isinstance(initial_value, rfc1902.Integer32):
            set_value = rfc1902.Integer32(str(new_value))
        elif isinstance(initial_value, rfc1902.IpAddress):
            set_value = rfc1902.IpAddress(str(new_value))
        elif isinstance(initial_value, rfc1902.OctetString):
            set_value = rfc1902.OctetString(str(new_value))
        elif isinstance(initial_value, rfc1902.TimeTicks):
            set_value = rfc1902.TimeTicks(str(new_value))
        elif isinstance(initial_value, rfc1902.Unsigned32):
            set_value = rfc1902.Unsigned32(str(new_value))
        else:
            raise RuntimeError("Unknown type %s" % type(initial_value))

        return set_value
示例#21
0
 def testPacking(self):
     """Test pack() function"""
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyString",
                                       "Hello world").pack(),
                      rfc1902.OctetString("Hello world"))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyInteger",
                                       18).pack(),
                      rfc1902.Integer(18))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyInteger",
                                       1804).pack(),
                      rfc1902.Integer(1804))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyEnum",
                                       "testing").pack(),
                      rfc1902.Integer(3))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyIpAddress",
                                       "10.11.12.13").pack(),
                      rfc1902.IpAddress("10.11.12.13"))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyObjectId",
                                       (1, 2, 3, 4)).pack(),
                      rfc1902.univ.ObjectIdentifier((1, 2, 3, 4)))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyTimeticks",
                                       timedelta(3, 2)).pack(),
                      rfc1902.TimeTicks(3 * 3600 * 24 * 100 + 2 * 100))
     self.assertEqual(basictypes.build("SNIMPY-MIB",
                                       "snimpyBits",
                                       [1, 7]).pack(),
                      rfc1902.Bits(b"\x41"))
示例#22
0
 def _set_port_tagged_status(self, port, status):
     dot1qVlanStaticEgressPorts = self.switch.snmp_get(
         ("dot1qVlanStaticEgressPorts", self.vid))
     new_port_list = VLAN._set_port_list_port_status(
         dot1qVlanStaticEgressPorts, port, status)
     if dot1qVlanStaticEgressPorts != new_port_list:
         self.switch.snmp_set((("dot1qVlanStaticEgressPorts", self.vid),
                               rfc1902.OctetString(new_port_list)))
示例#23
0
 def password(self, arg=None):
     """Set the password when server requires it."""
     oid = self.base_oid + '8.' + self.row
     if arg is None:
         return oid
     else:
         value = rfc1902.OctetString(arg)
         return (oid, value)
示例#24
0
 def username(self, arg=None):
     """Set the username when server requires it."""
     oid = self.base_oid + '7.' + self.row
     if arg is None:
         return oid
     else:
         value = rfc1902.OctetString(arg)
         return (oid, value)
示例#25
0
 def filename(self, arg=None):
     """Set filename when copying to/from a remote server."""
     oid = self.base_oid + '6.' + self.row
     if arg is None:
         return oid
     else:
         value = rfc1902.OctetString(arg)
         return (oid, value)
示例#26
0
    def test___str__(self):
        oid = oid_db.OidDbItem(
            oid='1.3.6.7.8',
            name='ifIndex',
            value=rfc1902.OctetString(hexValue='123456789'),
        )

        self.assertIsInstance(str(oid), str)
        self.assertTrue(str(oid))
示例#27
0
 def prettyPrint(self):
     if self.__state & self.stClean:
         s = rfc1902.OctetString()
         return '%s::%s%s%s' % (
             self.__modName, self.__symName,
             self.__indices and '.' or '',
             '.'.join([x.isSuperTypeOf(s) and '"%s"' % x.prettyPrint() or x.prettyPrint() for x in self.__indices])
         )
     else:
         raise SmiError('%s object not fully initialized' % self.__class__.__name__)
示例#28
0
文件: linksys.py 项目: sohonet/HEN
 def __setVLANName(self, vlan_name, vlan_ifindex):
     # use snmp to set the vlan name
     self.snmp.set(\
         OID.dot1qVlanStaticName + (vlan_ifindex,),\
         rfc1902.OctetString(str(vlan_name)))
     if self.snmp.getErrorStatus():
         log.debug("Error with " +
                   str(mylist[int(self.snmp.getErrorIndex()) - 1]))
         return -1
     return 0
示例#29
0
 def test_snmp_set(self):
     """
     Objective: Test if we can set data via snmp_set
     """
     client = snmp_client.SNMPClient(self.host, self.port)
     # syslocation
     oid = ((1, 3, 6, 1, 2, 1, 1, 6, 0), rfc1902.OctetString('TESTVALUE'))
     client.set_command(oid, callback=self.mock_callback)
     databus = conpot_core.get_databus()
     self.assertEqual('TESTVALUE', databus.get_value('sysLocation'))
示例#30
0
    def test___init__(self):
        oid = oid_db.OidDbItem(
            oid='1.3.6.7.8',
            name='ifIndex',
            value=rfc1902.OctetString(hexValue='123456789'),
        )

        self.assertEqual(rfc1902.ObjectIdentifier('1.3.6.7.8'), oid.oid)
        self.assertEqual('ifIndex', oid.name)
        self.assertEqual(b'\x124Vx\x90', oid.value)