PySNMP从4.4.12迁移至最新版:MibVariable类替代方案咨询
适配PySNMP最新版本替代MibVariable的方案
在PySNMP 5.x及以上版本中,原MibVariable类已被移除,取而代之的是ObjectType结合ObjectIdentity的组合,两者均位于pysnmp.hlapi子包中,可完全实现原MibVariable的所有功能。以下是具体适配方法:
核心替代逻辑
原代码中MibVariable(mib_name, var_name, index)的用法,直接替换为ObjectType(ObjectIdentity(mib_name, var_name, index))即可。如果是直接使用OID字符串(比如MibVariable('.1.3.6.1.2.1.1.1.0')),则替换为ObjectType(ObjectIdentity('.1.3.6.1.2.1.1.1.0'))。
代码示例对比
原PySNMP 4.4.12代码
from pysnmp.entity.rfc3413.oneliner.cmdgen import CmdGenerator, MibVariable from pysnmp.carrier.asyncore.dgram import udp cmdGen = CmdGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( CommunityData('public'), udp.UdpTransportTarget(('demo.snmplabs.com', 161)), MibVariable('SNMPv2-MIB', 'sysDescr', 0), MibVariable('IF-MIB', 'ifInOctets', 1) )
适配后的PySNMP最新版本代码
from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = getCmd( CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1)) )
额外说明
- CmdGenerator的替代:最新版本无需实例化
CmdGenerator,直接使用hlapi下的getCmd、setCmd、nextCmd等封装好的函数即可。 - 自定义MIB加载:如果原代码依赖自定义MIB,可使用
loadMibs函数加载,示例如下:
from pysnmp.hlapi import * # 加载自定义MIB文件 loadMibs('MY-CUSTOM-MIB') # 使用自定义MIB中的变量 errorIndication, errorStatus, errorIndex, varBinds = getCmd( CommunityData('public'), UdpTransportTarget(('192.168.1.1', 161)), ObjectType(ObjectIdentity('MY-CUSTOM-MIB', 'myDeviceStatus', 0)) )
- 变量绑定处理:返回的
varBinds格式与原版本兼容,仍可通过遍历或索引访问结果,比如:
for name, val in varBinds: print(f'{name.prettyPrint()} = {val.prettyPrint()}')
内容的提问来源于stack exchange,提问作者stesteve
相关产品推荐
相关产品推荐

