You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python pysnmp拉取交换机SNMP团体字列表问题咨询

问题排查及解决方法

1 核心问题:OID匹配错误

你当前使用的OID前缀.1.3.6.1.4.1.224属于阿尔卡特朗讯设备的私有MIB分支,不适用于思科设备,自然无法拉取到数据。

2 思科设备SNMP团体字表对应正确OID

思科设备的SNMP团体字配置存储在CISCO-SNMPv2-CONFIG-MIB的snmpCommunityTable表中,表前缀OID为:.1.3.6.1.4.1.9.9.96.1.1.1.1,常用字段如下:

  • .1.3.6.1.4.1.9.9.96.1.1.1.1.2:团体名字符串
  • .1.3.6.1.4.1.9.9.96.1.1.1.1.3:团体字所属的SNMP上下文
  • .1.3.6.1.4.1.9.9.96.1.1.1.1.4:团体字的访问权限(1=只读,2=读写)

3 前置权限要求

  • 拉取团体字配置属于设备敏感操作,不能使用默认只读团体字public,需要使用具备读写权限的SNMP团体字发起请求
  • 确认目标思科设备已开启SNMP配置查询权限,未配置SNMP访问限制规则拦截当前请求源IP

4 代码修改说明

你当前使用的hlapi.getCmd仅支持拉取单实例OID,团体字是多实例的表结构,需要使用hlapi.nextCmd遍历整表,修改后的参考代码如下:

from pysnmp import hlapi

def walk(target, oids, credentials, port=161, engine=hlapi.SnmpEngine(), context=hlapi.ContextData()):
    handler = hlapi.nextCmd(
        engine,
        credentials,
        hlapi.UdpTransportTarget((target, port)),
        context,
        *construct_object_types(oids),
        lexicographicMode=False
    )
    return fetch(handler, 10) # 最多返回10条团体字记录,可根据实际调整
    
def construct_object_types(list_of_oids):
    object_types = []
    for oid in list_of_oids:
        object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid)))
    return object_types
    
def fetch(handler, count):
    result = []
    for i in range(count):
        try:
            error_indication, error_status, error_index, var_binds = next(handler)
            if not error_indication and not error_status:
                for var_bind in var_binds:
                    result.append({
                        "oid": str(var_bind[0]),
                        "value": cast(var_bind[1])
                    })
            else:
                raise RuntimeError('Got SNMP error: {0}'.format(error_indication))
        except StopIteration:
            break
    return result
    
def cast(value):
    try:
        return int(value)
    except (ValueError, TypeError):
        try:
            return float(value)
        except (ValueError, TypeError):
            try:
                return str(value)
            except (ValueError, TypeError):
                pass
    return value

def getSNMPCommunities(ip, rw_community):
    try:
        # 遍历团体名字段OID
        communities = walk(ip, ['.1.3.6.1.4.1.9.9.96.1.1.1.1.2'], hlapi.CommunityData(rw_community))
        return [item["value"] for item in communities]
    except Exception as e:
        print(f"查询错误: {e}")
        return None
        
# 替换为实际设备IP和具备读写权限的团体字
snmpCommunities = getSNMPCommunities('10.0.0.1', '你的读写团体字')
print(snmpCommunities)

补充:老版本IOS兼容说明

部分运行老旧IOS版本的思科设备,使用CISCO-MIB分支的单实例OID即可查询:

  • .1.3.6.1.4.1.9.2.1.4:只读团体字
  • .1.3.6.1.4.1.9.2.1.5:读写团体字

内容的提问来源于stack exchange,提问作者user2122589

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:24:02