我正在使用 PySNMP。在我的程序中,我需要执行各种 SNMP 事务,这些事务为不同的函数
nextCmd
、getCmd
和 setCmd
重用相同的参数。为了简单起见,假设我只使用 getCmd
函数。我知道这个函数可以对多个 OID 进行操作,但这不是我当前的需要。下面我刚刚提取了托管设备的系统名称。
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData(snmp_community, mpModel=1),
UdpTransportTarget((target, 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0))
))
假设稍后在我的脚本中我需要从同一设备轮询正常运行时间。而不必像这样再次创建大部分代码:
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData(snmp_community, mpModel=1),
UdpTransportTarget((target, 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysUpTime', 0))
))
如何将
getCmd
函数与其他 static
参数一起存储,然后将 OID
传递到变量/函数中,以便可以最小化我的代码?
最简单的方法是将其包装在另一个函数中:
def standard_call(oid):
cmd = getCmd(SnmpEngine(),
CommunityData(snmp_community, mpModel=1),
UdpTransportTarget((target, 161)),
ContextData(),
# Plug in the oid
ObjectType(ObjectIdentity('SNMPv2-MIB', oid, 0)))
return next(cmd)
standard_call('sysUpTime')
standard_call('sysName')
注意更改的部分如何成为参数,而其他所有内容如何成为函数的主体。一般来说,这就是解决“泛化问题”的方法。
这可以通过从传入的元组构造
ObjectTypes
来扩展:
def standard_call(*identity_args):
# Construct the ObjectTypes we need
obj_types = [ObjectType(ObjectIdentity(*arg_tup)) for arg_tup in identity_args]
cmd = getCmd(SnmpEngine(),
CommunityData(snmp_community, mpModel=1),
UdpTransportTarget((target, 161)),
ContextData(),
# Spread the list of ObjectTypes as arguments to getCmd
*obj_types)
return next(cmd)
standard_call(('SNMPv2-MIB', 'sysName', 0),
('SNMPv2-MIB', 'sysServices', 0),
('CISCO-FLASH-MIB', 'ciscoFlashCopyEntryStatus', 13))
使用
functools.partial
来绑定一些参数怎么样?
from functools import partial
from pysnmp.hlapi import *
getCmd = partial(
getCmd, SnmpEngine(), CommunityData('public'),
UdpTransportTarget(('demo.pysnmp.com', 161)),
ContextData())
errorIndication, errorStatus, errorIndex, varBinds = next(
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)),
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysUpTime', 0))))