基于 snmptrad 示例的 SharpSNMP 实现停止工作

问题描述 投票:0回答:1

我正在基于 Sharp-SNMP 库(snmptrapd)中包含的示例制作一个应用程序原型,以从 SNMP 协议获取一些数据,但已完全停止工作,由于某种未知原因停止工作,但不抛出任何异常,编译并执行得好。

问题在于事件永远不会发生。

依赖关系:

  • Microsoft 的 Unity 容器
  • SharpSNMP 库
  • SourceGrid (Windows.Forms)

我必须指出,直到两天前,这还很有效,但现在,我已经没有想法了。 (而且我没有修改我的代码中的一些激进的东西)。

C# 代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Security;
using Lextm.SharpSnmpLib.Messaging;
using Lextm.SharpSnmpLib.Pipeline;
using Lextm.SharpSnmpLib.Mib;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.Utility;
using System.Configuration;
using SourceGrid;

namespace Kraken
{
    public partial class frmConsola : Form
    {
        internal static IUnityContainer Container { get; private set; }
        private SnmpEngine engine;

        // Delegates ....
        private delegate void MostrarMensajeDelegate(SourceGrid.Grid oGrd, DateTime eventTime, String eventType, IPAddress agentAddress, String Elemento, String Valor);

        public frmConsola()
        {
            InitializeComponent();
            this.crear_demonio_trampas();
            this.crear_grid();
        }

        private void crear_grid()
        {
            grdData.BorderStyle = BorderStyle.FixedSingle;

            grdData.ColumnsCount = 6;
            grdData.FixedRows = 1;
            grdData.Rows.Insert(0);

            grdData[0, 0] = new SourceGrid.Cells.ColumnHeader("Id");
            grdData[0, 1] = new SourceGrid.Cells.ColumnHeader("Hora");
            grdData[0, 2] = new SourceGrid.Cells.ColumnHeader("Tipo");
            grdData[0, 3] = new SourceGrid.Cells.ColumnHeader("Agente");
            grdData[0, 4] = new SourceGrid.Cells.ColumnHeader("Elemento");
            grdData[0, 5] = new SourceGrid.Cells.ColumnHeader("Valor");
            grdData.AutoSizeCells();
        }

        public void MostrarMensaje(SourceGrid.Grid oGrd, DateTime eventTime, String eventType, IPAddress agentAddress, String Elemento, String Valor)
        {
            int r = 0;
            if (!oGrd.IsDisposed)
            {
                r = oGrd.Rows.Count;
                oGrd.Rows.Insert(r);
                oGrd[r, 0] = new SourceGrid.Cells.Cell(r.ToString(), typeof(string));
                oGrd[r, 1] = new SourceGrid.Cells.Cell("?", typeof(string));
                oGrd[r, 2] = new SourceGrid.Cells.Cell(eventType, typeof(string));
                oGrd[r, 3] = new SourceGrid.Cells.Cell(agentAddress.ToString(), typeof(string));
                oGrd[r, 4] = new SourceGrid.Cells.Cell(Elemento, typeof(string));
                oGrd[r, 5] = new SourceGrid.Cells.Cell(Valor, typeof(string));
                grdData.AutoSizeCells();
            }
            else
            {
                throw (new ObjectDisposedException(oGrd.Name.ToString()));
            }
        }

        private void crear_demonio_trampas()
        {
            Container = new UnityContainer().LoadConfiguration("snmptrapd");
            var users = Container.Resolve<UserRegistry>();
            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
            users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
                                                                         new MD5AuthenticationProvider(new OctetString("authentication"))));
            // -------------- Plantas de fuerza ----------------------
            users.Add(new OctetString("PCC"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("peacct"), DefaultPrivacyProvider.DefaultPair);
            // -------------------------------------------------------
            var trapv1 = Container.Resolve<TrapV1MessageHandler>("TrapV1Handler");
            trapv1.MessageReceived += WatcherTrapV1Received;
            var trapv2 = Container.Resolve<TrapV2MessageHandler>("TrapV2Handler");
            trapv2.MessageReceived += WatcherTrapV2Received;
            var inform = Container.Resolve<InformRequestMessageHandler>("InformHandler");
            inform.MessageReceived += WatcherInformRequestReceived;
            this.engine = Container.Resolve<SnmpEngine>();
        }

        private void WatcherInformRequestReceived(object sender, InformRequestMessageReceivedEventArgs e)
        {
            string sTipo = "";
            uint[] codigo;
            Object[] oParams = new Object[6];
            oParams[0] = this.grdData;
            oParams[1] = new DateTime(e.InformRequestMessage.TimeStamp);
            codigo = e.InformRequestMessage.Enterprise.ToNumerical();
            foreach (int num in codigo)
            {
                if (sTipo != null)
                    sTipo += ".";
                sTipo += num.ToString();
            }
            oParams[2] = sTipo;
            oParams[3] = null;
            oParams[4] = e.InformRequestMessage.Variables()[0].ToString();
            oParams[5] = "";
            BeginInvoke(new MostrarMensajeDelegate(MostrarMensaje), oParams);
        }

        private void WatcherTrapV2Received(object sender, TrapV2MessageReceivedEventArgs e)
        {
            string sTipo = "";
            uint[] codigo;
            Object[] oParams = new Object[6];
            oParams[0] = this.grdData;
            oParams[1] = new DateTime(e.TrapV2Message.TimeStamp);
            codigo = e.TrapV2Message.Enterprise.ToNumerical();
            foreach (int num in codigo)
            {
                if (sTipo != null)
                    sTipo += ".";
                sTipo += num.ToString();
            }
            oParams[2] = sTipo;
            oParams[3] = null;
            oParams[4] = e.TrapV2Message.Variables()[0].Id.ToString();
            oParams[5] = e.TrapV2Message.Variables()[0].Data.ToString();
            BeginInvoke(new MostrarMensajeDelegate(MostrarMensaje), oParams);
        }

        private void WatcherTrapV1Received(object sender, TrapV1MessageReceivedEventArgs e)
        {
            string sTipo = "";
            uint[] codigo;
            Object[] oParams = new Object[6];
            oParams[0] = this.grdData;
            oParams[1] = new DateTime(e.TrapV1Message.TimeStamp);
            codigo = e.TrapV1Message.Enterprise.ToNumerical();
            foreach (int num in codigo)
            {
                if (sTipo != null)
                    sTipo += ".";
                sTipo += num.ToString();
            }
            oParams[2] = sTipo;
            oParams[3] = e.TrapV1Message.AgentAddress;
            oParams[4] = e.TrapV1Message.Variables()[0].Id.ToString();
            oParams[5] = e.TrapV1Message.Variables()[0].Data.ToString();
            //DateTime eventTime, String eventType, IPAddress agentAddress, String infoText
            BeginInvoke(new MostrarMensajeDelegate(MostrarMensaje), oParams);
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            this.engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 162));
            this.engine.Start();
            this.txtStatus.Text = "Iniciando Captura ...";
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.engine.Stop();
            this.txtStatus.Text = "... Finalizando Captura.";
        }

    }
}

应用程序配置

<?xml version="1.0"?>
<configuration>
    <configSections>
      <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
    </configSections>
    <startup>
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    </startup>
    <unity>
      <namespace name="Lextm.SharpSnmpLib.Pipeline"/>
      <namespace name="Lextm.SharpSnmpLib.Messaging"/>
      <namespace name="Lextm.SharpSnmpLib.Security"/>
      <namespace name="Lextm.SharpSnmpLib.Mib"/>
      <namespace name="Lextm.SharpSnmpLib"/>
      <assembly name="SharpSnmpLib"/>
      <assembly name="SharpSnmpLib.Engine"/>
      <assembly name="SharpSnmpLib.Mib"/>
      <aliases>
        <add alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/>
      </aliases>
      <containers>
        <container name="snmptrapd">
          <!-- users -->
          <register type="UserRegistry">
            <lifetime type="singleton"/>
            <constructor>
              <param name="users" dependencyType="User[]"/>
            </constructor>
          </register>
          <!-- message handler settings-->
          <register type="MessageHandlerFactory" name="MessageFactory">
            <lifetime type="singleton"/>
            <constructor>
              <param name="mappings">
                <array>
                  <!--here we only have four-->
                  <dependency name="TRAPV1"/>
                  <dependency name="TRAPV2"/>
                  <dependency name="INFORM"/>
                  <dependency name="ALL"/>
                </array>
              </param>
            </constructor>
          </register>
          <register type="HandlerMapping" name="TRAPV1">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="v1"/>
              <param name="command" value="TRAPV1"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="TrapV1Handler"/>
            </constructor>
          </register>
          <register type="HandlerMapping" name="TRAPV2">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="v2,v3"/>
              <param name="command" value="TRAPV2"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="TrapV2Handler"/>
            </constructor>
          </register>
          <register type="HandlerMapping" name="INFORM">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="v2,v3"/>
              <param name="command" value="INFORM"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="InformHandler"/>
            </constructor>
          </register>
          <register type="HandlerMapping" name="ALL">
            <lifetime type="singleton"/>
            <constructor>
              <param name="version" value="*"/>
              <param name="command" value="*"/>
              <param name="handler" dependencyType="IMessageHandler" dependencyName="NullHandler"/>
            </constructor>
          </register>
          <register type="IMessageHandler" mapTo="TrapV1MessageHandler" name="TrapV1Handler">
            <lifetime type="singleton"/>
          </register>
          <register type="IMessageHandler" mapTo="TrapV2MessageHandler" name="TrapV2Handler">
            <lifetime type="singleton"/>
          </register>
          <register type="IMessageHandler" mapTo="InformRequestMessageHandler" name="InformHandler">
            <lifetime type="singleton"/>
          </register>
          <register type="IMessageHandler" mapTo="NullMessageHandler" name="NullHandler">
            <lifetime type="singleton"/>
          </register>
          <!-- application factory and its parts -->
          <register type="SnmpApplicationFactory">
            <lifetime type="singleton"/>
            <constructor>
              <!--<param name="logger" />-->
              <param name="store" dependencyType="ObjectStore"/>
              <param name="membershipProvider" dependencyType="IMembershipProvider" dependencyName="Composed"/>
              <param name="factory" dependencyType="MessageHandlerFactory"/>
            </constructor>
          </register>
          <register type="ObjectStore">
            <lifetime type="singleton"/>
          </register>
          <!-- this is the membership provider -->
          <register type="IMembershipProvider" mapTo="ComposedMembershipProvider" name="Composed">
            <lifetime type="singleton"/>
            <constructor>
              <param name="providers">
                <array>
                  <dependency name="v1"/>
                  <dependency name="v2"/>
                  <dependency name="v3"/>
                </array>
              </param>
            </constructor>
          </register>
          <register type="IMembershipProvider" mapTo="Version1MembershipProvider" name="v1">
            <lifetime type="singleton"/>
            <constructor>
              <param name="getCommunity" dependencyType="OctetString" dependencyName="get"/>
              <param name="setCommunity" dependencyType="OctetString" dependencyName="set"/>
            </constructor>
          </register>
          <register type="IMembershipProvider" mapTo="Version2MembershipProvider" name="v2">
            <lifetime type="singleton"/>
            <constructor>
              <param name="getCommunity" dependencyType="OctetString" dependencyName="get"/>
              <param name="setCommunity" dependencyType="OctetString" dependencyName="set"/>
            </constructor>
          </register>
          <register type="IMembershipProvider" mapTo="Version3MembershipProvider" name="v3">
            <lifetime type="singleton"/>
          </register>
          <register type="OctetString" name="get">
            <lifetime type="singleton"/>
            <constructor>
              <param name="content" value="public"/>
            </constructor>
          </register>
          <register type="OctetString" name="set">
            <lifetime type="singleton"/>
            <constructor>
              <param name="content" value="public"/>
            </constructor>
          </register>
          <!-- Engine -->
          <register type="SnmpEngine">
            <lifetime type="singleton"/>
            <constructor>
              <param name="factory" dependencyType="SnmpApplicationFactory"/>
              <param name="listener" dependencyType="Listener"/>
              <param name="group" dependencyType="EngineGroup"/>
            </constructor>
          </register>
          <register type="Listener">
            <lifetime type="singleton"/>
            <property name="Users" dependencyType="UserRegistry"/>
          </register>
        </container>
      </containers>
    </unity>
</configuration>
c# .net snmp unity-interception sharp-snmp
1个回答
1
投票

调试时,首先请熟悉管道模型,

https://docs.lextudio.com/blog/honeycell-drops-snmp-pipeline-and-our-agent-demo-89986da1a5da

然后,连接调试器并检查您使用的 ListenerBinding (https://github.com/lextm/sharpsnmplib/blob/master/SharpSnmpLib/Messaging/ListenerBinding.cs) 是否从线路接收到任何 SNMP 数据包。

之后,继续处理管道 SnmpApplication 的下一个对象 (https://github.com/lextm/sharpsnmplib/blob/master/SharpSnmpLib/Pipeline/SnmpApplication.cs)。

逐步您可能会发现为什么没有触发事件。

此外,您也可以订阅 SnmpEngine.ExceptionRaished 来查看是否有异常发生。

© www.soinside.com 2019 - 2024. All rights reserved.