我在python中需要一个SNMP代理,它侦听特定端口并响应基本的SNMP命令(如GTE,SET,GETNEXT ……等)
如果有人有代码,请回复此帖.
解决方法:
在pysnmp web-site处有一组SNMP命令响应程序脚本.
这是一个简单的基于PySNMP的命令响应程序,它使用/ tmp中的文本文件作为MIB数据存储.
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.smi import instrum, error
from pysnmp.proto.api import v2c
snmpEngine = engine.SnmpEngine()
config.addSocketTransport(
snmpEngine,
udp.domainName,
udp.UdpTransport().openServerMode(('127.0.0.1', 1161))
)
config.addV1System(snmpEngine, 'my-area', 'public', contextName='my-context')
config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1,3,6), (1,3,6))
snmpContext = context.SnmpContext(snmpEngine)
class FileInstrumController(instrum.AbstractMibInstrumController):
def readVars(self, vars, acInfo=(None, None)):
try:
return [ (o,v2c.OctetString(open('/tmp/%s.txt' % o, 'r').read())) for o,v in vars ]
except IOError:
raise error.SmiError
def writeVars(self, vars, acInfo=(None, None)):
try:
for o,v in vars:
open('/tmp/%s.txt' % o, 'w').write(str(v))
return vars
except IOError:
raise error.SmiError
snmpContext.registerContextName(
v2c.OctetString('my-context'), # Context Name
FileInstrumController() # Management Instrumentation
)
cmdrsp.GetCommandResponder(snmpEngine, snmpContext)
cmdrsp.SetCommandResponder(snmpEngine, snmpContext)
snmpEngine.transportDispatcher.jobStarted(1)
try:
snmpEngine.transportDispatcher.runDispatcher()
except:
snmpEngine.transportDispatcher.closeDispatcher()
raise
请记住,这个脚本只是一个启动器,它不处理一些极端情况.