我正在尝试编写一个SNMP代理,可以用来监视python进程。为此,我编写了一个使用pysnmp实现SNMP代理的类。
该代理的核心部分工作正常(即,我可以使用snmpwalk询问代理,并且返回的数据是正确的)。为了更新代理MIB值,我在自己的线程中运行了dispatcher()。我的问题是,当使用snmpwalk与代理交谈时,我会超时(snmpwalk正确地遍历MIB,但随后超时)。
有人知道我做错了什么吗?
代理代码如下:
import logging
from pysnmp import debug
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdrsp, context
from pysnmp.smi import exval
import threading
formatting = '[%(asctime)s-%(levelname)s]-(%(module)s) %(message)s'
logging.basicConfig(level=logging.DEBUG, format=formatting, )
class SNMPAgent(object):
def _main(self):
logging.debug("Creating SNMP Agent....")
self._snmpEngine = engine.SnmpEngine()
config.addTransport(
self._snmpEngine,
udp.domainName,
udp.UdpTransport().openServerMode((self._agentHost, self._agentPort))
)
config.addV1System(self._snmpEngine, 'my-area', self._communityName)
config.addVacmUser(self._snmpEngine,
2,
'my-area',
'noAuthNoPriv',
(1, 3, 6),
(1, 3, 6))
snmpContext = context.SnmpContext(self._snmpEngine)
mibBuilder = snmpContext.getMibInstrum().getMibBuilder()
mibBuilder.loadModules('HOST-RESOURCES-MIB')
self._mibInstrum = snmpContext.getMibInstrum()
self._hostRunTable, = mibBuilder.importSymbols('HOST-RESOURCES-MIB', 'hrSWRunEntry')
self._instanceId = self._hostRunTable.getInstIdFromIndices(1)
# The following shows the OID name mapping
#
# hrSWRunTable 1.3.6.1.2.1.25.4.2 <TABLE>
# hrSWRunEntry 1.3.6.1.2.1.25.4.2.1 <SEQUENCE>
# hrSWRunIndex 1.3.6.1.2.1.25.4.2.1.1 <Integer32>
# hrSWRunName 1.3.6.1.2.1.25.4.2.1.2 <InternationalDisplayString> 64 Char
# hrSWRunID 1.3.6.1.2.1.25.4.2.1.3 <ProductID>
# hrSWRunPath 1.3.6.1.2.1.25.4.2.1.4 <InternationalDisplayString> 128 octets
# hrSWRunParameters 1.3.6.1.2.1.25.4.2.1.5 <InternationalDisplayString> 128 octets
# hrSWRunType 1.3.6.1.2.1.25.4.2.1.6 <INTEGER>
# hrSWRunStatus 1.3.6.1.2.1.25.4.2.1.7 <INTEGER> <<===== This is the key variable used by Opennms
self._setVars()
cmdrsp.GetCommandResponder(self._snmpEngine, snmpContext)
cmdrsp.SetCommandResponder(self._snmpEngine, snmpContext)
cmdrsp.NextCommandResponder(self._snmpEngine, snmpContext)
cmdrsp.BulkCommandResponder(self._snmpEngine, snmpContext)
def runAgent(self):
'''
Run the Agent
'''
t = threading.Thread(target=self._runAgentFunc, args = ())
t.daemon = True
t.start()
def _runAgentFunc(self):
try:
self._snmpEngine.transportDispatcher.jobStarted(1)
self._snmpEngine.transportDispatcher.runDispatcher()
except:
self._snmpEngine.transportDispatcher.closeDispatcher()
raise
def updateAgentStatus(self, runStatus, text1, text2):
self._mibDict = {"hrSWRunIndex" : 1,
"hrSWRunName" : self._name,
"hrSWRunID" : self._enterpriseMIB,
"hrSWRunPath" : text1[:128] if text1 is not None else '',
"hrSWRunParameters" : text2[:128] if text1 is not None else '',
"hrSWRunType" : 4,
"hrSWRunStatus" : 1
}
self._setVars()
def _setVars(self):
varBinds = self._mibInstrum.writeVars((
(self._hostRunTable.name + (1,) + self._instanceId, self._mibDict["hrSWRunIndex"]),
(self._hostRunTable.name + (2,) + self._instanceId, self._mibDict["hrSWRunName"]), # <=== Must match OpenNMS service-name variable
(self._hostRunTable.name + (3,) + self._instanceId, self._mibDict["hrSWRunID" ]), #
(self._hostRunTable.name + (4,) + self._instanceId, self._mibDict["hrSWRunPath"]),
(self._hostRunTable.name + (5,) + self._instanceId, self._mibDict["hrSWRunParameters"]),
(self._hostRunTable.name + (6,) + self._instanceId, self._mibDict["hrSWRunType"]), # Values are ==> unknown(1), operatingSystem(2), deviceDriver(3), application(4)
(self._hostRunTable.name + (7,) + self._instanceId, self._mibDict["hrSWRunStatus"]) #<<=== This is the status number OpenNMS looks at Values are ==> running(1), runnable(2), notRunnable(3), invalid(4)
))
def __init__(self, name, host, port, community, text1='Service up', text2=''):
'''
#=======================================================================
# Constructor
# name -- the (process) name the agent should publish (must match
# the openNMS name
# host -- the host name or ip the agent will run on
# port -- the port the snmp agent will listen on
# community -- the community name the agent will use (usually 'public')
# text1 -- the first status text string published (128 char max)
# text2 -- the second status text string published (128 char max)
#=======================================================================
'''
self._name = name
self._agentHost = host
self._agentPort = port
self._communityName = community
self._enterpriseMIB = (1, 3, 6, 1, 4, 1, 50000, 0) # Made up for now
self._mibInstrum = None
self._snmpEngine = None
self._dataChanged = False
self._mibDict = {"hrSWRunIndex" : 1,
"hrSWRunName" : self._name,
"hrSWRunID" : self._enterpriseMIB,
"hrSWRunPath" : text1[:128] if text1 is not None else '',
"hrSWRunParameters" : text2[:128] if text1 is not None else '',
"hrSWRunType" : 4,
"hrSWRunStatus" : 1
}
self._main()
我调用此代码如下(这只是测试我可以更改状态):
from SNMPAgent import SNMPAgent
from time import sleep
agent = SNMPAgent("test", "127.0.0.1", 12345, "public", "This is my test message 1", "This is my test message 2")
agent.runAgent()
sleep(10) # Wait for it to start
while True:
agent.updateAgentStatus(3, "Oh no", "Something is wrong!")
sleep(30)
agent.updateAgentStatus(2, "Whew", "Everything is fixed")
sleep(30)
要遍历代理MIB,我使用:
snmpwalk -v 2c -c public -n my-context 127.0.0.1:12345 1.3.6.1.2.1.25.4.2
这显示了数据更新,但在遍历MIB结束时,代理超时:
HOST-RESOURCES-MIB::hrSWRunIndex.1 = INTEGER: 1
HOST-RESOURCES-MIB::hrSWRunName.1 = STRING: "test"
HOST-RESOURCES-MIB::hrSWRunID.1 = OID: SNMPv2-SMI::enterprises.50000.0
HOST-RESOURCES-MIB::hrSWRunPath.1 = STRING: "Whew"
HOST-RESOURCES-MIB::hrSWRunParameters.1 = STRING: "Everything is fixed"
HOST-RESOURCES-MIB::hrSWRunType.1 = INTEGER: application(4)
HOST-RESOURCES-MIB::hrSWRunStatus.1 = INTEGER: running(1)
Timeout: No Response from 127.0.0.1:12345
启用pysnmp调试会显示由未设置特定OID的整数值导致的序列化错误:
[2017-01-13 02:05:18,387-DEBUG]-(debug) generateResponseMsg: Message:
version='version-2c'
community=public
data=PDUs:
response=ResponsePDU:
request-id=1950819527
error-status='noError'
error-index=0
variable-bindings=VarBindList:
VarBind:
name=1.3.6.1.2.1.25.5.1.1.1.1
=_BindValue:
value=ObjectSyntax:
simple=SimpleSyntax:
integer-value=<no value>
2017-01-13 02:05:18,387 pysnmp: generateResponseMsg: serialization failure: Uninitialized ASN.1 value ("__eq__" attribute looked up)
[2017-01-13 02:05:18,387-DEBUG]-(debug) generateResponseMsg: serialization failure: Uninitialized ASN.1 value ("__eq__" attribute looked up)
2017-01-13 02:05:18,388 pysnmp: StatusInformation: {'errorIndication': <pysnmp.proto.errind.SerializationError object at 0x10162f828>}
[2017-01-13 02:05:18,388-DEBUG]-(debug) StatusInformation: {'errorIndication': <pysnmp.proto.errind.SerializationError object at 0x10162f828>}
您可能应该确保为所有非默认SNMP表列设置了值。
作为补充说明,您似乎从主线程和SNMP代理线程管理MIB,而无需显式同步。这可能会导致比赛条件。。。
我一直在寻找一种在SNMP代理运行期间使用pysnmp动态更新SNMP表的方法。但到目前为止没有运气。。。 该表已经在MIB文件中定义(见下文),但似乎我需要覆盖其“readGet()”方法,以便从当前系统状态返回正确的数据。 根据http://pysnmp.sourceforge.net/examples/v3arch/asyncore/agent/cmdrsp/agent-side-mib-i
我正在使用多线程执行插入操作。我使用了带注释的方法,我的方法是注释。但我无法执行插入操作,导致出现以下异常。 异常线程"Thread-21"javax.persistence.Transaction必需异常:在org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:96)在sun.reflect.Native
关于Spring WebClient我有一个问题 在我的应用程序中,我需要做许多类似的API调用,有时我需要更改调用中的头(身份验证令牌)。所以问题来了,在这两个选择中,什么更好: > 为所有传入的MyService.class请求创建一个WebClient,方法是将其设置为字段,如下代码所示: 谢谢你。
我想编写一个spring boot批处理应用程序,其中我有一个充满事件的数据库表。我想做的是有一个多线程的spring boot批处理应用程序,它将以这种方式工作: 我想有5个线程运行,每个线程将保留一个偏移量来跟踪它读取的事件,以便没有其他线程再次读取相同的事件。我想怎么做: 所以我希望能够在数据库表中为每个线程保留偏移量。有没有办法让Spring Boot环境以这种方式工作?
问题内容: 一段时间以来,我一直在多线程环境中使用HttpClient。对于每个线程,当它启动连接时,它将创建一个全新的HttpClient实例。 最近,我发现使用这种方法可能导致用户打开太多端口,并且大多数连接处于TIME_WAIT状态。 http://www.opensubscriber.com/message/commons-httpclient- dev@jakarta.apache.or
我的程序使用ZMQ进行通信。也就是说,服务器(C、linux)创建一个XPUB套接字,然后在一个线程中读取它,在另一个线程中发布数据(写入)。 客户端(java、jzmq、linux)创建一个SUB套接字,并订阅使用它。 一段时间后,服务器端在读取线程中接收SIGABRT。 什么可能是问题的根源?在不同的线程中读/写或创建XPUB/SUB对? 如果问题是在多线程中,那么使用XPUB套接字的正确范例