为何Oracle Linux 9上pysnmp getCmd返回int 0而非Integer对象?
为何不同pysnmp版本返回的errorStatus类型不同?
核心原因:pysnmp版本迭代的API变更
你遇到的差异完全是因为pysnmp版本不同导致的API设计调整:
- CentOS 7上的
pysnmp-4.2.5是较旧版本,当时的oneliner API设计中,getCmd()返回的errorStatus是封装好的Integer枚举对象,自带错误名称(比如noError)和对应数值,目的是让开发者直观理解错误语义。 - Oracle Linux 9上的
pysnmp 4.4.12属于较新版本,官方对oneliner API做了简化,把errorStatus直接返回为Python原生int类型,更轻量化,错误名称需要手动通过枚举映射获取。
兼容处理方法
如果需要在新版本中获取错误名称,或者做跨版本兼容,可以这么处理:
手动映射错误名称
from pysnmp.proto.rfc1902 import NamedValues # 定义SNMP错误状态映射表 snmp_error_map = NamedValues( ('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5), ('noAccess', 6), ('wrongType', 7), ('wrongLength', 8), ('wrongEncoding', 9), ('wrongValue', 10), ('noCreation', 11), ('inconsistentValue', 12), ('resourceUnavailable', 13), ('commitFailed', 14), ('undoFailed', 15), ('authorizationError', 16), ('notWritable', 17), ('inconsistentName', 18) ) # 从int类型的errorStatus获取名称 error_name = snmp_error_map.getName(errorStatus)跨版本兼容代码
from pysnmp.proto.rfc1902 import NamedValues snmp_error_map = NamedValues(...) # 同上的映射表 errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(...) # 兼容新旧版本的错误状态处理 if hasattr(errorStatus, 'prettyPrint'): # 旧版本(4.2.x):直接取对象的名称和数值 error_name = errorStatus.prettyPrint() error_code = int(errorStatus) else: # 新版本(4.4.x):用int值映射名称 error_code = errorStatus error_name = snmp_error_map.getName(error_code)
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

