Ejemplo n.º 1
0
        private void snmpAgentThread_ReceiveEvent(object sender, ReceiveEventArgs re)
        {
            int version = SnmpPacket.GetProtocolVersion(re.message, re.message.Length);

            if (version == (int)SnmpVersion.Ver2)
            {
                SnmpV2Packet inPacket = new SnmpV2Packet();
                try
                {
                    inPacket.decode(re.message, re.message.Length);
                }
                catch (Exception ex)
                { }
                if (inPacket.Pdu.Type == PduType.Get)
                {
                    foreach (Vb vb in inPacket.Pdu.VbList)
                    {
                        var value = "Sample";
                        Console.WriteLine($"Request received on {re.inEndPoint.Address}:{re.inEndPoint.Port} : {vb.Oid}");
                        Console.WriteLine($"Answering : {vb.Oid} = {value}");
                        SendResponse(vb.Oid, value, re.inEndPoint);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private static void configTrap(TrapMessage trap, int ver, SnmpPacket packet)
        {
            trap.SnmpVersion = (SnmpVersionType)ver;
            trap.ReceiveTime = System.DateTime.Now;
            if (trap.SnmpVersion == SnmpVersionType.Ver1)
            {
                ((TrapV1Message)trap).SnmpVersion = (SnmpVersionType)ver;
                ((TrapV1Message)trap).Enterprise  = ((SnmpV1TrapPacket)packet).TrapPdu.Enterprise.ToString();
                ((TrapV1Message)trap).GenericTrap = ((SnmpV1TrapPacket)packet).TrapPdu.Generic.ToString();
                ((TrapV1Message)trap).Specific    = ((SnmpV1TrapPacket)packet).TrapPdu.Specific.ToString();
                ((TrapV1Message)trap).TimeStamp   = ((SnmpV1TrapPacket)packet).TrapPdu.TimeStamp.ToString();
                ((TrapV1Message)trap).Community   = ((SnmpV1TrapPacket)packet).Community.ToString();
                return;
            }
            TrapDesc trapDesc = new TrapDesc();

            trapDesc.TrapObjectID      = packet.Pdu.TrapObjectID.ToString();
            trapDesc.TrapSysUpTime     = packet.Pdu.TrapSysUpTime.ToString();
            trapDesc.ErrorIndex        = packet.Pdu.ErrorIndex.ToString();
            trapDesc.ErrorStatus       = packet.Pdu.ErrorStatus.ToString();
            trapDesc.ErrorStatusString = SnmpError.ErrorMessage(packet.Pdu.ErrorStatus);
            if (trap.SnmpVersion == SnmpVersionType.Ver2)
            {
                ((TrapV2Message)trap).Community = ((SnmpV2Packet)packet).Community.ToString();
                ((TrapV2Message)trap).TrapDesc  = trapDesc;
                return;
            }
            ((TrapV3Message)trap).EngineId     = ((SnmpV3Packet)packet).USM.EngineId.ToString();
            ((TrapV3Message)trap).SecurityName = ((SnmpV3Packet)packet).USM.SecurityName.ToString();
            ((TrapV3Message)trap).TrapDesc     = trapDesc;
        }
Ejemplo n.º 3
0
        private System.Collections.Generic.Dictionary <string, string> ReceiveResponseWithLeafVB(LeafVarBinding leafVb, Pdu pdu, UdpTarget target, IAgentParameters param)
        {
            if (leafVb.VarBindings.Count < 1)
            {
                throw new System.ArgumentNullException("The variables for the " + pdu.Type + " opertion is emtpy.");
            }
            pdu.VbList.Clear();
            this.configPduVb(leafVb, pdu);
            SnmpPacket snmpPacket = target.Request(pdu, param);

            this.validateResponse(snmpPacket, pdu);
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            foreach (Vb current in snmpPacket.Pdu.VbList)
            {
                if (current.Value.Type != SnmpConstants.SMI_NOSUCHINSTANCE && current.Value.Type != SnmpConstants.SMI_NOSUCHOBJECT && current.Value.Type != SnmpConstants.SMI_ENDOFMIBVIEW)
                {
                    string key = current.Oid.ToString();
                    if (!dictionary.ContainsKey(key))
                    {
                        dictionary.Add(key, current.Value.ToString());
                    }
                }
            }
            return(dictionary);
        }
Ejemplo n.º 4
0
        public void ParseSnmpGet1()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet1, Packet1.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet1, Packet1.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.True(packet.IsRequest);
            Assert.False(packet.IsResponse);

            Assert.Equal(38, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(1, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);

            Assert.Equal(new Oid("1.3.6.1.2.1.1.2.0"), vb.Oid);
        }
        /// <summary>
        /// Sends data, if socket is not connected, try to send to all clients.
        /// </summary>
        /// <param name="bytes">The byte array to send.</param>
        /// <returns>True, if all bytes has been sent</returns>
        public override bool Send(byte[] bytes)
        {
            var packet    = new SnmpPacket(SnmpCommunity, bytes.ToAsciiString(), Method);
            var sentBytes = Socket.Send(packet.Payload, packet.Payload.Length, SocketFlags.None);

            return(sentBytes == packet.Payload.Length);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// SNMP请求回调方法
        /// </summary>
        /// <param name="result"></param>
        /// <param name="packet"></param>
        private void SnmpCallbackFun(AsyncRequestResult result, SnmpPacket packet)
        {
            string logMsg = string.Format("SNMP异步请求结果: AsyncRequestResult = {0}", result);

            Log.Info(logMsg);

            if (result == AsyncRequestResult.NoError)
            {
                SnmpV2Packet packetv2 = (SnmpV2Packet)packet;

                if (packetv2 == null)
                {
                    Log.Error("SNMP request error, response is null.");
                    return;
                }

                CDTLmtbPdu lmtPdu = new CDTLmtbPdu();
                bool       rs     = SnmpPdu2LmtPdu(packetv2, m_SnmpAsync.m_target, lmtPdu, 0, false);

                // TODO
                // 发消息
            }

            return;
        }
Ejemplo n.º 7
0
        public void ParseSnmpGet7()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet7, Packet7.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet7, Packet7.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.True(packet.IsRequest);
            Assert.False(packet.IsResponse);

            Assert.Equal(41, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(3, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130104"), vb.Oid);

            vb = packet.Pdu.GetVb(1);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130102"), vb.Oid);

            vb = packet.Pdu.GetVb(2);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.5.10.14130400"), vb.Oid);
        }
Ejemplo n.º 8
0
        public void ParseSnmpV2cGet1()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(V2cPacket1, V2cPacket1.Length);

            Assert.Equal(ESnmpVersion.Ver2, packetVersion);

            var packet = new SnmpV2Packet();

            packet.Decode(V2cPacket1, V2cPacket1.Length);

            Assert.Equal("CISCO", packet.Community.ToString());

            Assert.False(packet.IsRequest);
            Assert.True(packet.IsResponse);

            Assert.Equal(2029159714, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(1, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);

            Assert.Equal(new Oid("1.0.8802.1.1.1.1.2.1.1.6.3"), vb.Oid);
            Assert.Equal(3, (vb.Value as Integer32).Value);
        }
Ejemplo n.º 9
0
        public void ParseSnmResponse2()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet2, Packet2.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet2, Packet2.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.False(packet.IsRequest);
            Assert.True(packet.IsResponse);

            Assert.Equal(38, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(1, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);

            Assert.Equal(new Oid("1.3.6.1.2.1.1.2.0"), vb.Oid);
            Assert.Equal((byte)(EAsnType.Constructor | EAsnType.Sequence), vb.Type);
            Assert.Equal((byte)EAsnType.ObjectId, vb.Value.Type);
            Assert.Equal(new Oid("1.3.6.1.4.1.2001.1.1.1.297.93.1.27.2.2.1"), vb.Value);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Funkcja realizująca polecenie GetNext agenta SNMP.
        /// SnmpVersion: SnmpVersion.Ver1 lub SnmpVersion.Ver2 lub SnmpVersion.Ver3. Zalecana Ver2.
        /// oidList: Lista identyfikatorów OID, których obiekty ma znalezc funkcja.
        /// </summary>
        /// <param name="version"></param>
        /// <param name="oid"></param>
        /// <param name="agent"></param>
        /// <returns></returns>
        public SnmpPacket GetNextRequest(SnmpVersion version, string[] oidList, IPAddress agent)
        {
            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);

            foreach (var oid in oidList)
            {
                pdu.VbList.Add(oid);
            }

            // SNMP community name
            OctetString community = new OctetString(snmp.Community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);

            // Set SNMP version to 1 (or 2)
            param.Version = version;

            // Make SNMP request
            SnmpPacket result = target.Request(pdu, param);


            return(result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Sends an SNMP request for the given OIDs.
        /// </summary>
        /// <param name="oids">The OIDs to request via SNMP.</param>
        /// <returns>The response SnmpPacket with the data.</returns>
        private SnmpPacket SendRequest(IEnumerable <Oid> oids)
        {
            var pduType = PduType.Get;

            Interlocked.CompareExchange(ref nextRequestId, 0, int.MaxValue); // wrap the request ID
            var requestId = Interlocked.Increment(ref nextRequestId);
            Pdu pdu       = new Pdu(pduType)
            {
                RequestId = requestId // 0 --> generate random ID on encode, anyhting else --> use that value for request ID
            };

            foreach (Oid item in oids)
            {
                pdu.VbList.Add(item);
            }

            log.Debug($"Using request ID '{requestId}' for PDU with {pdu.VbCount} elements to {this.Address}");

            using (var target = new UdpTarget((IPAddress)this.Address, this.Options.Port, Convert.ToInt32(this.Options.Timeout.TotalMilliseconds), this.Options.Retries))
            {
                SnmpPacket result = target.Request(pdu, this.QueryParameters);

                SnmpAbstraction.RecordSnmpRequest(this.Address, pdu, result);

                return(result);
            }
        }
Ejemplo n.º 12
0
        /// <inheritdoc />
        public VbCollection Query(IEnumerable <Oid> oids)
        {
            if (this.disposedValue)
            {
                throw new ObjectDisposedException(nameof(SnmpLowerLayer), "The object is already disposed off. Cannot execute any more commands on it.");
            }

            if (oids == null)
            {
                throw new ArgumentNullException(nameof(oids), "The list of OIDs to query is null");
            }

            SnmpPacket response = this.SendRequest(oids);

            if (response == null)
            {
                throw new HamnetSnmpException($"Query for {oids.Count()} OIDs from {this.Address} produced 'null' response", this.Address?.ToString());
            }

            // ErrorStatus other then 0 is an error returned by the Agent - see SnmpConstants for error definitions
            if (response.Pdu.ErrorStatus != 0)
            {
                // agent reported an error with the request
                var ex = new HamnetSnmpException($"Error in SNMP reply from device '{this.Address}': Error status {response.Pdu.ErrorStatus} at index {response.Pdu.ErrorIndex}, requested OIDs were '{string.Join(", ", response.Pdu.VbList.Select(o => o.Oid.ToString()))}'", this.Address?.ToString());
                log.Info(ex.Message);
                throw ex;
            }

            return(response.Pdu.VbList);
        }
Ejemplo n.º 13
0
 private void ReceiveTrap(object sender, SnmpPacket snmpPacket)
 {
     foreach (var vb in snmpPacket.GetValues())
     {
         trapListenerDataGridView.Rows.Add(vb.Oid.ToString(), vb.Value.ToString(),
                                           SnmpConstants.GetTypeName(vb.Value.Type),
                                           DateTime.Now.ToString("G"), snmpPacket.Version);
     }
 }
Ejemplo n.º 14
0
        public static SnmpPacket getNextRequest(string OID, string host, UdpTarget target, AgentParameters param)
        {
            Pdu pdu = new Pdu(PduType.GetNext);

            pdu.VbList.Add(OID);
            SnmpPacket result = (SnmpPacket)target.Request(pdu, param);

            return(result);
        }
Ejemplo n.º 15
0
            /// <summary>
            /// Records an SNMP in performance counter.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <param name="result">The result.</param>
            public void Record(Pdu request, SnmpPacket result)
            {
                this.TotalNumberOfRequestPdus  += request.VbCount;
                this.TotalNumberOfResponsePdus += result.Pdu.VbCount;

                if (result.Pdu.ErrorStatus != 0)
                {
                    ++this.TotalNumberOfErrorResponses;
                }
            }
Ejemplo n.º 16
0
        /// <summary>
        /// Records an SNMP in performance counter.
        /// </summary>
        /// <param name="destinationAddress">The destination IP address that this request has been sent to.</param>
        /// <param name="request">The request.</param>
        /// <param name="result">The result.</param>
        internal void Record(IpAddress destinationAddress, Pdu request, SnmpPacket result)
        {
            try
            {
                if (destinationAddress == null)
                {
                    log.Error("Failed to record for performance count: destinationAddress == null");
                    return;
                }

                if (request == null)
                {
                    log.Error("Failed to record for performance count: request == null");
                    return;
                }

                if (result == null)
                {
                    log.Error("Failed to record for performance count: result == null");
                    return;
                }

                this.overallResultsBacking.Record(request, result);

                // per address results:
                PerformanceSingleResultSet singleResultSet;
                if (!this.resultsPerDeviceMutable.TryGetValue((IPAddress)destinationAddress, out singleResultSet))
                {
                    singleResultSet = new PerformanceSingleResultSet();

                    // Note: It's crucial that we put exactly the same object in both dictionaries !
                    this.resultsPerDeviceMutable.TryAdd((IPAddress)destinationAddress, singleResultSet);
                    this.resultsPerDeviceInterfaced.TryAdd((IPAddress)destinationAddress, singleResultSet);
                }

                singleResultSet.Record(request, result);

                // per request type results:
                if (!this.resultsPerRequestTypeMutable.TryGetValue(request.Type.ToString(), out singleResultSet))
                {
                    singleResultSet = new PerformanceSingleResultSet();

                    // Note: It's crucial that we put exactly the same object in both dictionaries !
                    this.resultsPerRequestTypeMutable.TryAdd(request.Type.ToString(), singleResultSet);
                    this.resultsPerRequestTypeInterfaced.TryAdd(request.Type.ToString(), singleResultSet);
                }

                singleResultSet.Record(request, result);
            }
            catch (Exception ex)
            {
                // eat it up - this is crude but the simple small recording of stats shall not interrupt anything useful
                log.Error("Exception during statistics recording", ex);
            }
        }
Ejemplo n.º 17
0
 public static VbCollection GetValues(this SnmpPacket snmpPacket)
 {
     if (snmpPacket is SnmpV1TrapPacket)
     {
         return(((SnmpV1TrapPacket)snmpPacket).Pdu.VbList);
     }
     else
     {
         return(snmpPacket.Pdu.VbList);
     }
 }
Ejemplo n.º 18
0
        public static bool SendSNMPRequest(Pdu pdu, IPAddress ip, out SnmpPacket packet, SnmpVersion version = SnmpVersion.Ver2, string community = "public", int port = 161, int timeout = 1000, int retry = 1)
        {
            // Define agent parameters class
            AgentParameters agentParams = new AgentParameters(new OctetString(community))
            {
                Version = version,
            };

            packet = null;
            try
            {
                UdpTarget  target = new UdpTarget(ip, port, timeout, retry);
                SnmpPacket res;
                // Keep looping through results until end of table
                try
                {
                    res = target.Request(pdu, agentParams);
                }
                catch (Exception ex)
                {
                    LoggingHelper.LogEntry(SystemCategories.GeneralError, $"{ex.Message} {ex.StackTrace}");
                    target.Close();
                    return(false);
                }

                #region Validate request
                if (res.Version != version)
                {
                    LoggingHelper.LogEntry(SystemCategories.GeneralError, "Received wrong SNMP version response packet.");
                    target.Close();
                    return(false);
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    LoggingHelper.LogEntry(SystemCategories.GeneralError, $"SNMP agent returned error {res.Pdu.ErrorStatus} for request Vb index {res.Pdu.ErrorIndex}");
                    target.Close();
                    return(false);
                }
                #endregion

                target.Close();

                packet = res;
                return(true);
            }
            catch (Exception ex)
            {
                LoggingHelper.LogEntry(SystemCategories.GeneralError, $"{ex.Message} {ex.StackTrace}");
            }
            return(false);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Initialize SNMP packet class with agent parameters. In this class, SNMP community name is
 /// set in SNMPv1 and SNMPv2 packets.
 /// </summary>
 /// <param name="packet">Packet class to initialize</param>
 public void InitializePacket(SnmpPacket packet)
 {
     if (packet is SnmpV1Packet pktv1)
     {
         pktv1.Community.Set(_community);
     }
     else if (packet is SnmpV2Packet pktv2)
     {
         pktv2.Community.Set(_community);
     }
     else
     {
         throw new SnmpInvalidVersionException("Invalid SNMP version.");
     }
 }
Ejemplo n.º 20
0
 private void validateResponse(SnmpPacket response, Pdu pdu)
 {
     if (response == null)
     {
         throw new SnmpException("Request failed: There is no response to this " + pdu.Type + " request.");
     }
     if (response.Pdu.ErrorStatus != 0 && response.Pdu.ErrorStatus != 2)
     {
         throw new SnmpException("Receive failed with error status <" + response.Pdu.ErrorStatus + ">.");
     }
     if (response.Pdu.Type == PduType.Report)
     {
         throw new SnmpException("Report response.");
     }
 }
Ejemplo n.º 21
0
        public string GetSend(string getOid, string Version, string communityRead, string IP, int Port)
        {
            OctetString community = new OctetString(communityRead);

            AgentParameters param = new AgentParameters(community);

            if (Version == "V1")
            {
                param.Version = SnmpVersion.Ver1;
            }
            if (Version == "V2")
            {
                param.Version = SnmpVersion.Ver2;
            }
            IpAddress agent = new IpAddress(IP);

            UdpTarget target = new UdpTarget((IPAddress)agent, Port, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);

            try
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(getOid);

                if (Version == "V1")
                {
                    result = (SnmpV1Packet)target.Request(pdu, param);
                }
                if (Version == "V2")
                {
                    result = (SnmpV2Packet)target.Request(pdu, param);
                }
            }
            catch (Exception e) { }

            target.Close();

            using (IDbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DeviceConnection"].ConnectionString))
            {
                connection.Query <WalkTowerDevice>($"update WalkTowerDevice set Type='{result.Pdu.VbList[0].Value.ToString()}' where WalkOID='{getOid}' and IP='{IP}'");
            }
            return(result.Pdu.VbList[0].Value.ToString());
        }
Ejemplo n.º 22
0
        public void Listen()
        {
            var ipEndPoint = new IPEndPoint(IPAddress.Any, 162);

            Task.Run(async() => {
                var run = true;
                while (run)
                {
                    try {
                        using (var udpListener = new UdpClient(ipEndPoint)) {
                            var udpRecieveResult = await udpListener.ReceiveAsync();
                            var recievedData     = udpRecieveResult.Buffer;

                            int protocolVersion = SnmpPacket.GetProtocolVersion(recievedData, recievedData.Length);

                            switch (protocolVersion)
                            {
                            case (int)SnmpVersion.Ver1:
                                var snmpV1TrapPacket = new SnmpV1TrapPacket();
                                snmpV1TrapPacket.decode(recievedData, recievedData.Length);
                                RecieveTrap(snmpV1TrapPacket);
                                break;

                            case (int)SnmpVersion.Ver2:
                                var snmpV2Packet = new SnmpV2Packet();
                                snmpV2Packet.decode(recievedData, recievedData.Length);
                                RecieveTrap(snmpV2Packet);
                                break;

                            case (int)SnmpVersion.Ver3:
                                var snmpV3Packet = new SnmpV3Packet();
                                snmpV3Packet.decode(recievedData, recievedData.Length);
                                RecieveTrap(snmpV3Packet);
                                break;
                            }
                        }
                    }
                    catch (SocketException) {
                        ErrorMessageBox.Show($"Port {ipEndPoint.Port} is already used.");
                        run = false;
                    }
                    catch (Exception e) {
                        ErrorMessageBox.Show($"{e.Message}");
                    }
                }
            });
        }
Ejemplo n.º 23
0
        /// <summary>
        /// SNMP Operation Execute
        /// </summary>
        /// <example>Set operation in SNMP version 1:
        /// <code>
        /// </code>
        ///
        ///
        /// </example>
        /// <param name="version">SNMPAgentInfo. 对端SNMP Agent相关配置信息</param>
        /// <param name="pdu">PduType. 要执行的操作类型:Get/Set/GetNext/GetBulk</param>
        /// <param name="pdu">Vb[]. 操作参数</param>
        /// <returns>Result of the SNMP request in a IEnumerator<vb> </returns>
        public IEnumerable <Vb> Excute(SnmpAgentInfo peer, PduType pduType, IEnumerable <Vb> vbs)
        {
            //验证对端地址信息是否正确
            if (!this.ValidPeer(peer))
            {
                Log.Error("SnmpAgentInfo校验失败!");
                return(null);
            }

            //组装PDU
            Pdu pdu = this.PacketPdu(pduType, vbs);

            //GetBulk包需要设置NonRepeaters和MaxRepetitions两个字段
            if (PduType.GetBulk == pdu.Type)
            {
                pdu.NonRepeaters   = peer.NonRepeaters;
                pdu.MaxRepetitions = peer.MaxRepetitions;
            }

            using (var _target = new UdpTarget(peer.PeerAddress, peer.Port, peer.TimeOut, peer.RetryTime))
            {
                SnmpPacket result = null;
                try
                {
                    var param = new AgentParameters(peer.Version, new OctetString(peer.Community));
                    result = _target.Request(pdu, param);
                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message);
                    throw;
                }

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus == 0)
                    {
                        return(result.Pdu);
                    }

                    throw new SnmpErrorStatusException("Agent responded with an error", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                }
            }

            return(null);
        }
Ejemplo n.º 24
0
        private System.Collections.Generic.Dictionary <string, string> ReceiveResponseWithTableVB(TableVarBinding tableVb, Pdu pdu, UdpTarget target, IAgentParameters param)
        {
            if (string.IsNullOrEmpty(tableVb.TableEntryOid))
            {
                throw new System.ArgumentNullException("The TableEntryOid can not be null or empty.");
            }
            Oid oid  = new Oid(tableVb.TableEntryOid);
            Oid oid2 = null;

            if (string.IsNullOrEmpty(tableVb.ColumnOid))
            {
                oid2 = (Oid)oid.Clone();
            }
            else
            {
                oid2 = new Oid(tableVb.ColumnOid);
            }
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            while (oid2 != null)
            {
                pdu.VbList.Clear();
                pdu.VbList.Add(oid2);
                SnmpPacket snmpPacket = target.Request(pdu, param);
                this.validateResponse(snmpPacket, pdu);
                foreach (Vb current in snmpPacket.Pdu.VbList)
                {
                    if (!oid.IsRootOf(current.Oid))
                    {
                        oid2 = null;
                        break;
                    }
                    if (current.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                    {
                        oid2 = null;
                        break;
                    }
                    string key = current.Oid.ToString();
                    if (!dictionary.ContainsKey(key))
                    {
                        dictionary.Add(key, current.Value.ToString());
                        oid2 = current.Oid;
                    }
                }
            }
            return(dictionary);
        }
Ejemplo n.º 25
0
 public void CheckOIDs()
 {
     IsOnline();
     if (Online)
     {
         OctetString     community = new OctetString("public");
         AgentParameters param     = new AgentParameters(community);
         IpAddress       agent     = new IpAddress(IP);
         UdpTarget       target    = new UdpTarget((IPAddress)agent, 161, 2000, 1);
         Pdu             pdu       = new Pdu(PduType.Get);
         foreach (var oid in DeviceProps)
         {
             pdu.VbList.Add(oid.PropOID);
         }
         SnmpPacket result = target.Request(pdu, param);
         if (result != null)
         {
             if (result.Pdu.ErrorStatus != 0)
             {
                 throw new ArgumentException("Error in SNMP reply. Error {0} " +
                                             result.Pdu.ErrorStatus + "index" +
                                             result.Pdu.ErrorIndex);
             }
             else
             {
                 for (int i = 0; i < DeviceProps.Count; i++)
                 {
                     try
                     {
                         DeviceProps[i].PropValue = result.Pdu.VbList[i].Value.ToString();
                     }
                     catch (Exception)
                     {
                         continue;
                     }
                 }
             }
         }
         else
         {
             throw new Exception("No response received from SNMP agent.");
         }
         target.Close();
     }
 }
Ejemplo n.º 26
0
        public string GetSend(string getOid, string Version, string communityRead, string IP, int Port)
        {
            OctetString community = new OctetString(communityRead);

            AgentParameters param = new AgentParameters(community);

            if (Version == "V1")
            {
                param.Version = SnmpVersion.Ver1;
            }
            if (Version == "V2")
            {
                param.Version = SnmpVersion.Ver2;
            }
            IpAddress agent = new IpAddress(IP);

            UdpTarget target = new UdpTarget((IPAddress)agent, Port, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);

            try
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(getOid);

                if (Version == "V1")
                {
                    result = (SnmpV1Packet)target.Request(pdu, param);
                }
                if (Version == "V2")
                {
                    result = (SnmpV2Packet)target.Request(pdu, param);
                }
            }
            catch (Exception e) { }
            target.Close();
            deviceWalkData.UpdateWalkTowerDeviceGetSend(result, getOid, IP);
            return(result.Pdu.VbList[0].Value.ToString());
        }
Ejemplo n.º 27
0
        private void configVb(TrapMessage trap, int ver, SnmpPacket packet)
        {
            VbCollection vbList;

            if (ver == 0)
            {
                vbList = ((SnmpV1TrapPacket)packet).TrapPdu.VbList;
            }
            else
            {
                vbList = packet.Pdu.VbList;
            }
            new System.Text.StringBuilder();
            foreach (Vb current in vbList)
            {
                if (!trap.VarBindings.ContainsKey(current.Oid.ToString()))
                {
                    trap.VarBindings.Add(current.Oid.ToString(), current.Value.ToString());
                }
            }
        }
Ejemplo n.º 28
0
        public void ParseSnmpResponse8()
        {
            var packetVersion = SnmpPacket.GetProtocolVersion(Packet8, Packet8.Length);

            Assert.Equal(ESnmpVersion.Ver1, packetVersion);

            var packet = new SnmpV1Packet();

            packet.Decode(Packet8, Packet8.Length);

            Assert.Equal("public", packet.Community.ToString());

            Assert.False(packet.IsRequest);
            Assert.True(packet.IsResponse);

            Assert.Equal(41, packet.Pdu.RequestId);
            Assert.Equal(EPduErrorStatus.NoError, packet.Pdu.ErrorStatus);
            Assert.Equal(0, packet.Pdu.ErrorIndex);

            Assert.Equal(3, packet.Pdu.VbCount);

            var vb = packet.Pdu.GetVb(0);

            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130104"), vb.Oid);
            Assert.Equal((byte)EAsnType.OctetString, vb.Value.Type);
            Assert.Equal(new byte[] { 0x31, 0x37, 0x32, 0x2e, 0x33, 0x31, 0x2e, 0x31, 0x39, 0x2e, 0x32 }, vb.Value as OctetString);

            vb = packet.Pdu.GetVb(1);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.7.10.14130102"), vb.Oid);
            Assert.Equal((byte)EAsnType.OctetString, vb.Value.Type);
            Assert.Equal(new byte[] { 0x32, 0x35, 0x35, 0x2e, 0x32, 0x35, 0x35, 0x2e, 0x32, 0x35, 0x35, 0x2e, 0x30 }, vb.Value as OctetString);

            vb = packet.Pdu.GetVb(2);
            Assert.NotNull(vb);
            Assert.Equal(new Oid("1.3.6.1.4.1.253.8.64.4.2.1.5.10.14130400"), vb.Oid);
            Assert.Equal((byte)EAsnType.Integer, vb.Value.Type);
            Assert.Equal(1, vb.Value as Integer32);
        }
Ejemplo n.º 29
0
        private static void DoWork()
        {
            // Construct a socket and bind it to the trap manager port 162

            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 162);
            EndPoint   ep     = (EndPoint)ipep;

            socket.Bind(ep);
            // Disable timeout processing. Just block until packet is received
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);

            while (true)
            {
                byte[] indata = new byte[16 * 1024];
                // 16KB receive buffer
                int        inlen = 0;
                IPEndPoint peer  = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   inep  = (EndPoint)peer;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);
                }
                catch (Exception ex)
                {
                    Functions.AddTempLog(new List <string> {
                        ex.Message, ex.ToString()
                    });
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    // Check protocol version
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver2)
                    {
                        // Parse SNMP Version 2 TRAP packet
                        SnmpV2Packet pkt = new SnmpV2Packet();
                        pkt.decode(indata, inlen);
                        List <string> alarm = new List <string> {
                            inep.ToString(), pkt.Community.ToString()
                        };
                        List <string> trap = new List <string>();
                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            trap.Add(v.Value.ToString());
                        }
                        Functions.AddTempLog(trap);

                        if (trap.Count == 42)
                        {
                            IPCom     _ipcom     = new IPCom();
                            CiscoPort _ciscoPort = new CiscoPort();

                            string path = "C:\\Repository.db";
                            string _connectionString;
                            _connectionString = "Data Source=" + path + ";Version=3;";
                            using (var connection = new SQLiteConnection(_connectionString))
                            {
                                connection.Open();

                                using (var command = new SQLiteCommand("SELECT IP,Com,PortId FROM Ports WHERE JDSUPort = @_JDSUPort", connection))
                                {
                                    command.Parameters.Add("@_JDSUPort", DbType.String).Value = trap[27];



                                    try
                                    {
                                        using (var reader = command.ExecuteReader())
                                        {
                                            // int k = (int)command.ExecuteScalar();

                                            foreach (DbDataRecord record in reader)
                                            {
                                                try
                                                {
                                                    SimpleSnmp snmp = new SimpleSnmp(record["IP"].ToString(), record["Com"].ToString());



                                                    Pdu pdu = new Pdu(PduType.Set);
                                                    pdu.VbList.Add(new Oid(".1.3.6.1.2.1.2.2.1.7" + record["PortId"].ToString()), new Integer32(2));
                                                    snmp.Set(SnmpVersion.Ver2, pdu);
                                                }
                                                catch (Exception ex)
                                                {
                                                    alarm.Add(ex.ToString());
                                                }


                                                alarm.Add(record["IP"].ToString());
                                                alarm.Add(record["Com"].ToString());
                                                alarm.Add(record["PortId"].ToString());
                                                alarm.Add(trap[27].ToString());
                                            }
                                        }
                                    }

                                    catch (Exception ex)
                                    {
                                        alarm.Add(ex.ToString());
                                        alarm.Add("в базе данных нет такой записи");
                                    }
                                }
                            }
                            //  Functions.AddTempLog(alarm);
                        }
                        else
                        {
                            if (inlen == 0)
                            {
                                Functions.AddTempLog(new List <string> {
                                    "Zero length packet received."
                                });
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
        void SnmpAsyncResponseCallback(AsyncRequestResult result, SnmpPacket packet)
        {
            //If result is null then agent didn't reply or we couldn't parse the reply.
            if (result == AsyncRequestResult.NoError && packet != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (packet.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    TipMessage  = string.Format("SNMP应答数据包中有错误信息. Error {0} index {1}", packet.Pdu.ErrorStatus, packet.Pdu.ErrorIndex);
                    errorStatus = false;
                    NotifyPropertyChanged("TotalStatus");
                }
                else
                {
                    errorStatus = true;
                    //ifAdminStatus//ifOperStatus//ifInOctets //ifOutOctets
                    bool tempAdminStatus, tempOperStatus;
                    if (packet.Pdu.VbList[0].Value as Integer32 == 1)
                    {
                        tempAdminStatus = true;
                    }
                    else
                    {
                        tempAdminStatus = false;
                    }
                    if (packet.Pdu.VbList[1].Value as Integer32 == 1)
                    {
                        tempOperStatus = true;
                    }
                    else
                    {
                        tempOperStatus = false;
                    }
                    if (tempAdminStatus != adminStatus || tempOperStatus != operStatus)
                    {
                        adminStatus = tempAdminStatus;
                        operStatus  = tempOperStatus;
                        NotifyPropertyChanged("Status");
                        NotifyPropertyChanged("StatusDescr");
                        NotifyPropertyChanged("TotalStatus");
                        if (inSpeed != -1)
                        {
                            TipMessage = string.Format("AdminStatus:{0}\nOperStatus:{1}", adminStatus ? "up" : "down", operStatus ? "up" : "down");
                        }
                    }

                    if (inSpeed == -1)
                    {
                        //这次是第一次获取数据
                        oldInOctets   = packet.Pdu.VbList[2].Value as Counter32;
                        oldIOutOctets = packet.Pdu.VbList[3].Value as Counter32;
                        oldTime       = DateTime.Now;
                        inSpeed       = 0;
                        outSpeed      = 0;
                    }
                    else
                    {
                        newInOctets  = packet.Pdu.VbList[2].Value as Counter32;
                        newOutOctets = packet.Pdu.VbList[3].Value as Counter32;
                        DateTime now      = DateTime.Now;
                        double   interval = (now - oldTime).TotalSeconds;
                        oldTime       = now;
                        inSpeed       = Math.Round((newInOctets - oldInOctets) * 0.008 / interval, 2); //结果为 kb/s
                        outSpeed      = Math.Round((newOutOctets - oldIOutOctets) * 0.008 / interval, 2);
                        SpeedRealTime = string.Format("In: {0}kb/s; Out: {1}kb/s", inSpeed, outSpeed);
                        oldInOctets   = newInOctets;
                        oldIOutOctets = newOutOctets;
                        uiDispatcher.Invoke(new Action(() =>
                        {
                            DataPoint dpIn  = new DataPoint();
                            dpIn.XValue     = DateTime.Now;
                            dpIn.YValue     = inSpeed;
                            DataPoint dpOut = new DataPoint();
                            dpOut.XValue    = DateTime.Now;
                            dpOut.YValue    = outSpeed;
                            if (InSpeedDataPointList.Count >= 30)
                            {
                                InSpeedDataPointList.RemoveAt(0);
                            }
                            InSpeedDataPointList.Add(dpIn);
                            if (OutSpeedDataPointList.Count >= 30)
                            {
                                OutSpeedDataPointList.RemoveAt(0);
                            }
                            OutSpeedDataPointList.Add(dpOut);
                        }));
                        if (IsShowSpeedAlarm)
                        {
                            //SpeedAlarmStatus
                            bool tempSpeedAlarmStatus = (inSpeed <= maxInSpeed) && (outSpeed <= maxOutSpeed);
                            if (tempSpeedAlarmStatus != SpeedAlarmStatus)
                            {
                                SpeedAlarmStatus = tempSpeedAlarmStatus;
                                TipMessage       = string.Format("In:{0}kb/s{1};Out:{2}kb/s{3}", inSpeed, (inSpeed <= maxInSpeed) ? "正常" : "超限!", outSpeed, (outSpeed <= maxOutSpeed) ? "正常" : "超限!");
                            }
                        }
                    }
                }
            }
            else
            {
                TipMessage = "没有SNMP应答数据包";
            }
            target.Close();
        }