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

Ubuntu下PySNMP调用nextCmd报NameError错误求助

解决方案

这个错误本质是PySNMP版本的API不兼容或导入方式错误,以下是几种可行的解决办法:

1. 修正导入语句(适配PySNMP v4.x)

如果安装的是PySNMP v4.x系列,显式导入所需的API可以避免导入遗漏问题:

from pysnmp.hlapi import nextCmd, SnmpEngine, CommunityData, UdpTransportTarget, ContextData, ObjectType, ObjectIdentity

如果坚持用from pysnmp.hlapi import *,请确认没有安装多个版本的PySNMP导致冲突。

2. 降级到稳定兼容版本

如果当前装的是PySNMP v5.x+的新版本,其API结构有较大改动,nextCmd的位置和调用逻辑已变化。可以降级到v4.4.12这个稳定兼容版本:

pip3 uninstall pysnmp -y
pip3 install pysnmp==4.4.12

3. 适配新版本PySNMP API(v5.x+)

如果想保留最新版本,需要调整代码适配新的API结构,比如修改导入路径:

from pysnmp.hlapi.v3arch import *

def walk_Query_str(comm, IP, OID):
    query_str = []
    iterator = nextCmd(
        SnmpEngine(),
        CommunityData(comm, mpModel=1),
        UdpTransportTarget((IP, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(OID)),
        lexicographicMode=False
    )
    # 后续循环逻辑保持不变
    for errorIndication, errorStatus, errorIndex, varBinds in iterator:
        if errorIndication:
            print(errorIndication)
        elif errorStatus:
            print('%s at %s' % (
                errorStatus.prettyPrint(),
                errorIndex and varBinds[int(errorIndex) - 1][0] or '?'
            ))
        else:
            for varBind in varBinds:
                query_str.append(varBind[1].prettyPrint())
    return query_str

walk_Query_str('fan@solar', '172.21.2.32', '1.3.6.1.4.1.318.1.1.27.1.4.1.2.1.2.1')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:35:12