示例#1
0
        //SNMP set方法
        private void setSnmp(string oid, string host, int port, string value)
        {
            string hostIP;
            int    Port;
            string Oid;
            string Value;

            Oid    = oid;
            hostIP = host;
            Port   = port;
            Value  = value;

            //共同体类型
            OctetString     community = new OctetString("private");
            AgentParameters param     = new AgentParameters(community);

            //设置snmp版本
            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress(hostIP);

            //构建目标
            UdpTarget target = new UdpTarget((IPAddress)agent, port, 2000, 1);

            Pdu pdu = new Pdu(PduType.Set);

            pdu.VbList.Add(new SnmpSharpNet.Oid(Oid), new OctetString(Value));

            //发送snmp请求
            SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
        }
示例#2
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;
        }
示例#3
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);
                    }
                }
            }
        }
示例#4
0
        private string SendRequests(UdpTarget target, AgentParameters param)
        {
            try
            {
                SnmpV2Packet _indexResult = (SnmpV2Packet)target.Request(_index, param);
                SnmpV2Packet _descrResult = (SnmpV2Packet)target.Request(_descr, param);
                SnmpV2Packet _typeResult  = (SnmpV2Packet)target.Request(_type, param);

                if (_indexResult.Pdu.ErrorStatus != 0 || _descrResult.Pdu.ErrorStatus != 0 || _typeResult.Pdu.ErrorStatus != 0)
                {
                    Logger.Log("SNMP Request Error", Logger.MessageType.ERROR);
                    return("<color><red>ERROR: packet error status = " + _indexResult.Pdu.ErrorStatus.ToString() + " and not ZERO");
                }
                else
                {
                    for (int i = 0; i < _indexResult.Pdu.VbCount; i++)
                    {
                        _output += "Interface " + _indexResult.Pdu.VbList[i].Value.ToString() + ": Type " + _typeResult.Pdu.VbList[i].Value.ToString() + " -> " + _descrResult.Pdu.VbList[i].Value.ToString() + "\n";
                    }
                    Logger.Log("Successfully performed SNMP Device Request", Logger.MessageType.INFORM);
                    return(_output);
                }
            }
            catch (Exception)
            {
                Logger.Log("SNMP Request Error", Logger.MessageType.ERROR);
                return("<color><red>ERROR: sending requests failed");
            }
        }
示例#5
0
        private uint ParameterCountRequest(AgentParameters param, UdpTarget target)
        {
            Oid deviceNr = new Oid(_ifNr);
            Pdu devices  = new Pdu(PduType.Get);

            devices.VbList.Add(deviceNr);

            try
            {
                SnmpV2Packet devicesResult = (SnmpV2Packet)target.Request(devices, param);

                if (devicesResult.Pdu.ErrorStatus != 0)
                {
                    return(0);
                }
                else
                {
                    return(Convert.ToUInt32(devicesResult.Pdu.VbList[0].Value.ToString()));
                }
            }
            catch (Exception)
            {
                return(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);
        }
示例#7
0
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            OctetString community = new OctetString("public");

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

            // Set SNMP version to 1 (or 2)
            param.Version = SnmpVersion.Ver2;
            // Construct the agent address object
            // IpAddress class is easy to use here because
            //  it will try to resolve constructor parameter if it doesn't
            //  parse to an IP address
            IpAddress agent  = new IpAddress("127.0.0.1");
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            // Pdu class used for all requests
            Pdu    pdu = new Pdu(PduType.Get);
            string oid = whatShouldIAdd("Adding new property to PDU list");

            pdu.VbList.Add(oid);
            SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result.Pdu.ErrorStatus,
                                      result.Pdu.ErrorIndex);
                }
                else
                {
                    for (int i = 0; i < pdu.VbList.Count; i++)
                    {
                        resultString = String.Format("(0}) ({1}): {2}",
                                                     result.Pdu.VbList[0].Oid.ToString(),
                                                     SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type).ToString(),
                                                     result.Pdu.VbList[0].Value.ToString());
                        MessageBox.Show(resultString);
                        watchIterations = watchIterations + 1;
                        if (watchIterations > 5)
                        {
                            GeneratorsTimer.Enabled = false;
                        }
                    }
                }
            }

            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
        }
示例#8
0
        private void btnSNMPSend_Click(object sender, EventArgs e)
        {
            try
            {
                OctetString     community = new OctetString("public");
                AgentParameters param     = new AgentParameters(community);
                param.Version = SnmpVersion.Ver2;
                IpAddress agent = new IpAddress(txtCurrentIP.Text);

                UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, 161, 2000, 1);

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);


                foreach (DataGridViewRow dr in dgvInstructions.SelectedRows)
                {
                    pdu.VbList.Add(dr.Cells["InstructionBytes"].Value.ToString());
                }

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

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        txtReceivedBytesASCII.Text = String.Format("Error in SNMP reply. Error {0} index {1}",
                                                                   result.Pdu.ErrorStatus,
                                                                   result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        for (int i = 0; i < result.Pdu.VbList.Count; i++)
                        {
                            txtReceivedBytesASCII.Text += result.Pdu.VbList[i].Oid.ToString() + ", " + SnmpConstants.GetTypeName(result.Pdu.VbList[i].Value.Type) + ", " +
                                                          result.Pdu.VbList[i].Value.ToString() + ", " + dgvInstructions.SelectedRows[i].Cells["Explanation"].Value.ToString() + Environment.NewLine;
                        }
                    }
                }
                else
                {
                    //txtConsole.Text = String.Format("No response received from SNMP agent.");
                }
                target.Close();
            }
            catch (Exception exp)
            {
                txtReceivedBytesASCII.Text = exp.ToString();
            }
        }
示例#9
0
        private bool GetAllConfigurationPdu(UdpTarget target)
        {
            VbCollection vbCollection = new VbCollection();

            vbCollection.Add(conv4000ConvAInstalled.Default.oid);                        //0
            vbCollection.Add(conv4000ConvAFrequency.Default.oid);                        //1
            vbCollection.Add(conv4000ConvAMute.Default.oid);                             //2
            vbCollection.Add(conv4000ConvAConfigMuteMode.Default.oid);                   //3
            vbCollection.Add(conv4000ConvAAttenuator.Default.oid);                       //4
            vbCollection.Add(conv4000ConvASlope.Default.oid);                            //5
            vbCollection.Add(conv4000ConvAAttenuationOffset.Default.oid);                //6
            vbCollection.Add(conv4000convASpectrumInversion.Default.oid);                //7
            vbCollection.Add(conv4000ConvBInstalled.Default.oid);                        //8
            vbCollection.Add(conv4000ConvBFrequency.Default.oid);                        //9
            vbCollection.Add(conv4000ConvBMute.Default.oid);                             //10
            vbCollection.Add(conv4000ConvBConfigMuteMode.Default.oid);                   //11
            vbCollection.Add(conv4000ConvBAttenuator.Default.oid);                       //12
            vbCollection.Add(conv4000ConvBSlope.Default.oid);                            //13
            vbCollection.Add(conv4000convBSpectrumInversion.Default.oid);                //14
            vbCollection.Add(conv4000PSA12VFault.Default.oid);                           //15
            vbCollection.Add(conv4000PSA08VFault.Default.oid);                           //16
            vbCollection.Add(conv4000PSA05VFault.Default.oid);                           //17
            vbCollection.Add(conv4000PSB12VFault.Default.oid);                           //18
            vbCollection.Add(conv4000PSB08VFault.Default.oid);                           //19
            vbCollection.Add(conv4000PSB05VFault.Default.oid);                           //20
            vbCollection.Add(conv4000ConvARFLOFault.Default.oid);                        //21
            vbCollection.Add(conv4000ConvAIFLOFault.Default.oid);                        //22
            vbCollection.Add(conv4000ConvATempFault.Default.oid);                        //23
            vbCollection.Add(conv4000ConvBIFLOFault.Default.oid);                        //24
            vbCollection.Add(conv4000ConvBRFLOFault.Default.oid);                        //25
            vbCollection.Add(conv4000ConvBTempFault.Default.oid);                        //26
            vbCollection.Add(conv4000ExternalRefFault.Default.oid);                      //27
            try
            {
                var pdu      = Pdu.GetPdu(vbCollection);
                var param    = new AgentParameters(SnmpVersion.Ver2, new OctetString(pdu.Type == PduType.Get ? ReadCommunity : WriteCommunity));
                var response = target.Request(pdu, param);
                if (!(response is SnmpV2Packet))
                {
                    return(false);                                                                  // not a valid packet
                }
                if (response.Pdu.ErrorStatus != 0)
                {
                    return(false);                                                                  // an error occured
                }
                _result = (SnmpV2Packet)response;
                _logger.WriteMessage("Got results successfully.", DebugLevel.DEBUG);
                return(true);
            }
            catch
            {
                _logger.WriteMessage("An error occured in GetConfigurationPdu.", DebugLevel.ERROR);
                return(false);
            }
        }
示例#10
0
        /// <summary>
        /// 同步Set操作
        /// </summary>
        /// <param name="lmtPdu"></param>
        /// <param name="requestId"></param>
        /// <param name="strIpAddr"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public int SnmpSetSync(CDTLmtbPdu lmtPdu, out long requestId, string strIpAddr, long timeOut)
        {
            requestId = 0;

            Log.Debug("========== SnmpGetSync() Start ==========");
            string msg = string.Format("pars: lmtPdu={0}, requestId={1}, strIpAddr={2}, timeOut={3}"
                                       , lmtPdu, requestId, strIpAddr, timeOut);

            Log.Debug(msg);

            if (string.IsNullOrEmpty(strIpAddr))
            {
                Log.Error("参数strIpAddr为空");
                return(-1);
            }
            if (lmtPdu == null)
            {
                Log.Error("参数lmtPdu为空");
                return(-1);
            }

            // TODO: 根据基站ip获取Lmtor信息
            //LMTORINFO* pLmtorInfo = CDTAppStatusInfo::GetInstance()->GetLmtorInfo(remoteIpAddr);

            SnmpHelper snmp = m_SnmpSync;

            if (null == snmp)
            {
                msg = string.Format("基站[{0}]的snmp连接不存在,无法下发snmp命令");
                Log.Error(msg);
                return(-1);
            }

            // TODO
            lmtPdu.setReqMsgType((int)PduType.Set);


            Pdu pdu = new Pdu();
            // TODO:
            string community = "private";
            bool   rs        = LmtPdu2SnmpPdu(out pdu, lmtPdu, strIpAddr);

            SnmpV2Packet result = snmp.SetRequest(pdu);

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

            rs = SnmpPdu2LmtPdu(result, snmp.m_target, lmtPdu, 0, false);

            return(0);
        }
示例#11
0
        public override SnmpV2Packet GetRequest(Pdu pdu)
        {
            if (m_target == null)
            {
                Log.Error("SNMP m_target = null.");
                return(null);
            }

            if (pdu == null)
            {
                Log.Error("SNMP请求参数pdu为空");
                return(null);
            }

            // Log msg
            string       logMsg;
            SnmpV2Packet result = null;

            pdu.Type = PduType.Get;
            try
            {
                result = (SnmpV2Packet)m_target.Request(pdu, m_Param);
                if (null != result)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        logMsg = string.Format("Error in SNMP reply. Error {0} index {1}"
                                               , result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                        Log.Error(logMsg);
                    }
                    else
                    {
                        foreach (Vb vb in result.Pdu.VbList)
                        {
                            logMsg = string.Format("ObjectName={0}, Type={1}, Value={2}"
                                                   , vb.Oid.ToString(), SnmpConstants.GetTypeName(vb.Value.Type), vb.Value.ToString());
                            Log.Debug(logMsg);
                        }
                    }
                }
                else
                {
                    Log.Error("No response received from SNMP agent.");
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message.ToString());
                throw e;
            }


            return(result);
        }
示例#12
0
        //SNMP get方法
        private string getSnmp(string oid, string host, int port)
        {
            string hostIP;
            int    Port;
            string Oid;
            string get = "";

            Oid    = oid;
            hostIP = host;
            Port   = port;

            //共同体类型
            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            //设置snmp版本
            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress(hostIP);

            //构建目标
            UdpTarget target = new UdpTarget((IPAddress)agent, port, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);

            pdu.VbList.Add(Oid);

            //发送snmp请求
            SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    this.textBox1.Text += string.Format("Error in SNMP reply. Error {0} index {1} \r\n", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    //result.Pdu.VbList[0].Oid.ToString()
                    //SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type)
                    //result.Pdu.VbList[0].Value.ToString())
                    get = result.Pdu.VbList[0].Value.ToString();
                }
                target.Dispose();
            }
            return(get);
        }
示例#13
0
        public SnmpV2Packet GetNextRequest(Oid oid)
        {
            IpAddress agent  = new IpAddress(_agentsIP);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetNext);

            //Adding new property to PDU list
            pdu.VbList.Add(oid);

            // Make SNMP request
            SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, _param);

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    string errorMessage = String.Format("Error in SNMP reply. Error {0} index {1}",
                                                        result.Pdu.ErrorStatus.ToString(),
                                                        result.Pdu.ErrorIndex.ToString());
                    MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK);
                    return(null);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList

                    //DATABASE adding
                    string newOid   = result.Pdu.VbList[0].Oid.ToString();
                    string newValue = result.Pdu.VbList[0].Value.ToString();
                    string newType  = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type).ToString();
                    string newIp    = _agentsIP;
                    _oid = result.Pdu.VbList[0].Oid;
                    AddItemToDatabase(newOid, newValue, newType, newIp);

                    return(result);
                }
            }
            else
            {
                MessageBox.Show("No response received from SNMP agent.", "Error", MessageBoxButtons.OK);
                return(null);
            }
        }
示例#14
0
        /// <summary>
        /// 根据提供信息获取一个或多个snmp值,返回VbCollection,若出错则返回null
        /// </summary>
        /// <param name="ip">目标地址</param>
        /// <param name="requestOids">目标oid数组</param>
        /// <param name="errorMessage">输出错误信息</param>
        /// <param name="community">共同体字符串,默认public</param>
        /// <param name="port">端口,默认161</param>
        /// <param name="timeout">超时,默认2000ms</param>
        /// <param name="retry">重试次数,默认1次</param>
        /// <returns>返回VbCollection,若出错则返回null</returns>
        public static VbCollection GetResultsFromOids(IpAddress ip, string[] requestOids, out string errorMessage)
        {
            int             n     = requestOids.Length;
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(App.snmpCommunity));

            param.DisableReplySourceCheck = !App.snmpCheckSrcFlag;
            UdpTarget target = new UdpTarget((IPAddress)ip, App.snmpPort, App.snmpTimeout, App.snmpRetry);
            Pdu       pdu    = new Pdu(PduType.Get);

            for (int i = 0; i < requestOids.Length; i++)
            {
                pdu.VbList.Add(requestOids[i]);
            }
            SnmpV2Packet result = null;

            try
            {
                result = (SnmpV2Packet)target.Request(pdu, param);
            }
            catch (Exception ex)
            {
                errorMessage = "获取SNMP应答出现错误\n" + ex.Message;
                target.Close();
                return(null);
            }
            VbCollection vbs;

            if (result != null)
            {
                if (result.Pdu.ErrorStatus != 0)
                {
                    errorMessage = string.Format("SNMP应答数据包中有错误信息. Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                    target.Close();
                    return(null);
                }
                else
                {
                    vbs = result.Pdu.VbList;
                }
            }
            else
            {
                errorMessage = "没有SNMP应答数据包";
                target.Close();
                return(null);
            }
            errorMessage = "";
            target.Close();
            return(vbs);
        }
示例#15
0
        /// <summary>
        /// Send a response after a Get or Set command.
        /// </summary>
        /// <param name="oid">Oid of the response</param>
        /// <param name="value">Value</param>
        /// <param name="outEndPoint">Out endpoint</param>
        public void SendResponse(Oid oid, string value, IPEndPoint outEndPoint)
        {
            SnmpV2Packet outPacket  = new SnmpV2Packet();
            Pdu          pdu        = new Pdu(PduType.Response);
            VbCollection collection = new VbCollection();

            collection.Add(oid, new OctetString(value));
            pdu.SetVbList(collection);
            outPacket._pdu = pdu;
            byte[] outdata   = outPacket.encode();
            Socket outSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            outSocket.Connect(outEndPoint);
            outSocket.Send(outdata);
        }
示例#16
0
        private void btnGet_Click(object sender, EventArgs e)
        {
            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress("127.0.0.1");

            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.Get);
            //pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); //sysDescr //OID + VALUE
            //pdu.VbList.Add("1.3.6.1.2.1.1.2.0"); //sysObjectID
            //pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); //sysUpTime
            //pdu.VbList.Add("1.3.6.1.2.1.1.4.0"); //sysContact
            //pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName

            string oid = whatShouldIAdd("Adding new property to PDU list");

            pdu.VbList.Add(oid);

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

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                      result.Pdu.ErrorStatus,
                                      result.Pdu.ErrorIndex);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    resultString = String.Format("({0}) ({1}): {2}",
                                                 result.Pdu.VbList[0].Oid.ToString(),
                                                 SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type).ToString(),
                                                 result.Pdu.VbList[0].Value.ToString());
                    MessageBox.Show(resultString);
                }
            }
        }
示例#17
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}");
                    }
                }
            });
        }
        public IActionResult Start([FromBody] Setting setting)
        {
            OctetString community = new OctetString(setting.Community);

            AgentParameters param = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;

            IpAddress agent = new IpAddress(setting.AgentAddress);

            UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);

            pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName

            SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    return(Json(("Error in SNMP reply. Error {0} index {1}",
                                 result.Pdu.ErrorStatus,
                                 result.Pdu.ErrorIndex)));
                }
                else
                {
                    return(Json(("sysName({0}) ({1}): {2}",
                                 result.Pdu.VbList[4].Oid.ToString(),
                                 SnmpConstants.GetTypeName(result.Pdu.VbList[4].Value.Type),
                                 result.Pdu.VbList[4].Value.ToString())));
                }
            }
            else
            {
                return(Json("No response received from SNMP agent."));
            }
            target.Close();

            return(Json(setting));
        }
示例#19
0
        private bool SNMPDecodeData(SnmpV2Packet Result, Oid indexOid, Oid finalOid, bool InclusiveInterval, ISNMPDeviceDataDTO SNMPDeviceData)
        {
            bool nextEntry = true;

            if (Result != null && Result.Pdu.ErrorStatus == 0)
            {
                // Walk through returned variable bindings
                foreach (Vb ResBinding in Result.Pdu.VbList)
                {
                    // Check that retrieved Oid is higher than the limit or is the last block of leafs
                    if (ResBinding.Oid < finalOid || finalOid.IsRootOf(ResBinding.Oid) && InclusiveInterval)
                    {
                        //Check OID Value Type. If unknown we break loop and storage
                        EnumSNMPOIDType OIDType = (EnumSNMPOIDType)Enum.Parse(typeof(EnumSNMPOIDType), SnmpConstants.GetTypeName(ResBinding.Value.Type));

                        if (OIDType != EnumSNMPOIDType.Unknown)
                        {
                            ISNMPRawEntryDTO SNMPRawData = SNMPDeviceData.BuildSNMPRawEntry(ResBinding.Oid.ToString(), ResBinding.Value.ToString(), OIDType);
                        }
                        else
                        {
                            nextEntry = false;
                            break;
                        }

                        //Check if we have already drilled down all contents
                        if (ResBinding.Value.Type != SnmpConstants.SMI_ENDOFMIBVIEW)
                        {
                            indexOid.Set(ResBinding.Oid); //If we use = operator, we are changing references! In that case, ref keyword is mandatory
                            nextEntry = true;
                        }
                    }
                    else
                    {
                        nextEntry = false;
                        break;
                    }
                }
            }
            else
            {
                //Console.WriteLine("Error in SNMP reply. Error {0} index {1}", Result.Pdu.ErrorStatus, Result.Pdu.ErrorIndex);
            }

            return(nextEntry);
        }
示例#20
0
文件: JobSnmp.cs 项目: onixion/MAD
        private void ExecuteRequest(UdpTarget _target, AgentParameters _param)
        {
            const string _outOctetsString = "1.3.6.1.2.1.2.2.1.16";

            Oid _outOctets = new Oid(_outOctetsString + "." + ifEntryNr);

            Pdu _octets = new Pdu(PduType.Get);

            _octets.VbList.Add(_outOctets);

            try
            {
                SnmpV2Packet _octetsResult = (SnmpV2Packet)_target.Request(_octets, _param);

                if (_octetsResult.Pdu.ErrorStatus != 0)
                {
                    outp.outState = JobOutput.OutState.Failed;
                    Logging.Logger.Log("Something went wrong with reading the traffic. The Error Status of SNMP was not equal 0, but " + _octetsResult.Pdu.ErrorStatus.ToString(), Logging.Logger.MessageType.ERROR);
                }
                else
                {
                    uint _result = (uint)Convert.ToUInt64(_octetsResult.Pdu.VbList[0].Value.ToString()) - _lastRecord;
                    _lastRecord = (uint)Convert.ToUInt64(_octetsResult.Pdu.VbList[0].Value.ToString());

                    if (firstRun)
                    {
                        outp.GetOutputDesc("Bytes").dataObject = 0;
                    }
                    else
                    {
                        outp.GetOutputDesc("Bytes").dataObject = _result;
                    }

                    outp.outState = JobOutput.OutState.Success;
                    Logging.Logger.Log("Traffic Read reports Success", Logging.Logger.MessageType.DEBUG);
                }
            }
            catch (Exception ex)
            {
                outp.outState = JobOutput.OutState.Failed;
                Logging.Logger.Log("Something went wrong with reading the traffic. The message is: " + ex.Message, Logging.Logger.MessageType.ERROR);
            }
        }
示例#21
0
        private void ExecuteRequest(UdpTarget target, AgentParameters param)
        {
            Oid _name = new Oid("1.3.6.1.2.1.1.5.0");

            Pdu _namePacket = new Pdu(PduType.Get);

            _namePacket.VbList.Add(_name);

            try
            {
                SnmpV2Packet _nameResult = (SnmpV2Packet)target.Request(_namePacket, param);

                outp.outState = JobOutput.OutState.Success;
            }
            catch (Exception)
            {
                Logger.Log("SNMP Service seems to be dead", Logger.MessageType.ERROR);
                outp.outState = JobOutput.OutState.Failed;
            }
        }
示例#22
0
文件: Rtu.cs 项目: AKllX/Gemini
        void Update(object state)
        {
            SnmpV2Packet result = Target.GetUpdate();

            if(result == null)
            {
                Core.Log.ErrorFormat("Falha GET SNMP RTU {0}", Id);
            }
            else
            {
                if (result.Pdu.ErrorStatus != 0)
                {
                    Core.Log.ErrorFormat("Falha PDU SNMP RTU {0} ErrorStatus {1} Error Code {2}", Id, result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                }
                else
                {
                    this.UpdateCache(result);
                }
            }
        }
示例#23
0
        /// <summary>
        /// Обработчик события таймера
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                // Отключение
                timer.Enabled = false;
                // Адрес источника данных по SNMP
                // Адрес берется из конфигурации
                IpAddress peer = new IpAddress(Properties.Settings.Default.Host);

                // Параметры вызова по протоколу SNMP
                // Вторая версия протокола, community string public - чтение данных
                AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString("public"));
                // Точка подключения по SNMP
                UdpTarget target = new UdpTarget((System.Net.IPAddress)peer, 161, 2000, 1);
                // Список запрашиваемых данных и режим запроса - GET
                Pdu pdu = new Pdu(PduType.Get);

                // 1.3.6.1.2.1.1.1.0 - SysDescr
                // 1.3.6.1.2.1.1.3.0 - SysUpTime
                // Добавление OID в список запрашиваемых данных
                pdu.VbList.Add("1.3.6.1.2.1.1.1.0");
                pdu.VbList.Add("1.3.6.1.2.1.1.3.0");
                // Выполнение запроса по SNMP
                SnmpV2Packet res = (SnmpV2Packet)target.Request(pdu, param);
                foreach (Vb v in res.Pdu.VbList)
                {
                    EventLog.WriteEntry(v.ToString(), EventLogEntryType.Information, (int)EventID.TimerEvent);
                }
            }
            catch (Exception ex)
            {
                WriteException(ex);
            }
            finally
            {
                // Включение таймера
                timer.Enabled = true;
            }
        }
示例#24
0
文件: Program.cs 项目: lailasr/Gemini
        static void Main(string[] args)
        {
            Core.Start();

            SnmpTarget retAbelSantana = new SnmpTarget("10.7.5.150");

            retAbelSantana.InsertObject("batteryTemperaturesValue", ".1.3.6.1.4.1.12148.10.10.7.5.0");
            SnmpV2Packet result     = retAbelSantana.GetUpdate();
            IPEndpoint   myEndPoint = new IPEndpoint("0.0.0.0", 20500);
            Rtu          rtu        = new Rtu("Teste DNP3", myEndPoint, 2, 1);
            ChangeSet    changeSet;
            int          currentValue;

            while (true)
            {
                if (result != null)
                {
                    changeSet = new ChangeSet();
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        currentValue = Convert.ToInt32(result.Pdu.VbList[0].Value.ToString());
                        changeSet.Update(new Analog(currentValue, 1, DateTime.Now), 0);
                        Console.WriteLine("Atualizando valor da analógica para " + currentValue);
                        rtu.Outstation.Load(changeSet);
                    }
                }
                else
                {
                    Console.WriteLine("Erro SNMP Nulo");
                }
                Thread.Sleep(15000);
            }
        }
示例#25
0
        public void getData()
        {
            AgentParameters param = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;
            IpAddress agent  = new IpAddress(ipAddr);
            UdpTarget target = new UdpTarget((System.Net.IPAddress)agent, nPort, timeOut, retry);

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

                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP. Error {0}, Index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        response = result.Pdu.VbList[0].Value.ToString();

                        Console.WriteLine("Data is {0} .", result.Pdu.VbList[0].Value.ToString());
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP");
                }
            }
            target.Close();
        }
示例#26
0
 private bool GetCurrentInformation(UdpTarget target)
 {
     try
     {
         if (GetAllConfigurationPdu(target))
         {
             ParseCurrentInformation();
             return(true);
         }
         else
         {
             _logger.WriteMessage("GetAllconfigurationPdu", DebugLevel.ERROR);
         }
     }
     catch (Exception ex)
     {
         _logger.WriteMessage(ex.Message, DebugLevel.ERROR);
     }
     finally
     {
         _result = null;
     }
     return(false);
 }
示例#27
0
        public SNMPResultSet[] Walk(string pOID)
        {
            List <SNMPResultSet> snmpResults = new List <SNMPResultSet>();

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

            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            param.Version = SnmpVersion.Ver2;

            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)AgentIP, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(pOID); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk);

            // In this example, set NonRepeaters value to 0
            pdu.NonRepeaters = 0;
            // MaxRepetitions tells the agent how many Oid/Value pairs to return
            // in the response.
            pdu.MaxRepetitions = 5;

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                snmpResults.Add(new SNMPResultSet(v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()));

                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(snmpResults.ToArray());
        }
示例#28
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."
                                });
                            }
                        }
                    }
                }
            }
        }
示例#29
0
        public static void Check(CredentialsSnmp credentials)
        {
            // Populate the List of OID's to Get
            var asnItems = new Dictionary <string, SnmpAsnItem>
            {
                { BaseOid + "1.2.0", new SnmpAsnItem("Model") },
                { BaseOid + "1.3.0", new SnmpAsnItem("Firmware Version") },
                { BaseOid + "1.4.0", new SnmpAsnItem("Software Version") },
                { BaseOid + "1.5.0", new SnmpAsnItem("Serial Number") },
                { BaseOid + "6.1.0", new SnmpAsnItem("Alarms Present") },
                { BaseOid + "7.3.0", new SnmpAsnItem("Test Result Summary") },
                { BaseOid + "7.5.0", new SnmpAsnItem("Last Test Up Time") },

                { "1.3.6.1.2.1.1.3.0", new SnmpAsnItem("Up Time") },
                { "1.3.6.1.4.1.534.1.6.5.0", new SnmpAsnItem("Temperature") },
                { "1.3.6.1.4.1.534.1.6.6.0", new SnmpAsnItem("Humidity") }
            };

            var asnItemsLookup = new Dictionary <string, Vb>();

            // SNMP Query
            var snmpCommunity = new OctetString(credentials.Community);
            var agentParams   = new AgentParameters(snmpCommunity)
            {
                Version = SnmpVersion.Ver2
            };

            var agent  = new IpAddress(credentials.Host);
            var target = new UdpTarget((IPAddress)agent, Port, 2000, 1);

            var pdu = new Pdu(PduType.Get);

            foreach (var item in asnItems)
            {
                pdu.VbList.Add(item.Key);
            }

            var result = new SnmpV2Packet();

            try
            {
                result = (SnmpV2Packet)target.Request(pdu, agentParams);
            }
            catch (Exception ex)
            {
                if (ex.Message == "Request has reached maximum retries.")
                {
                    Error.WriteOutput("SNMP Request to " + credentials.Host + " with community " + credentials.Community + " has exceeded the maximum number of retries.");
                    return;
                }
            }

            if (result != null)
            {
                // Populate Results
                foreach (var item in result.Pdu.VbList)
                {
                    if (asnItems.ContainsKey(item.Oid.ToString()))
                    {
                        asnItems[item.Oid.ToString()].Vb = item;
                    }
                }

                // Build Reverse Lookup Dictionary
                foreach (var item in asnItems)
                {
                    asnItemsLookup.Add(item.Value.Description, item.Value.Vb);
                }

                var output = new Result();
                var model  = asnItemsLookup["Model"].Value.ToString();

                var message = model;
                message += " SN " + asnItemsLookup["Serial Number"].Value;
                message += " (SW v" + asnItemsLookup["Software Version"].Value;
                message += " / FW v" + asnItemsLookup["Firmware Version"].Value + ")";

                var globalMessage = "";

                Channel channel;

                // Humidity
                // TODO - This is untested code
                var tempStr = asnItemsLookup["Humidity"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null" && tempStr != "SNMP No-Such-Instance")
                    {
                        channel = new Channel
                        {
                            Description = "Humidity",
                            Unit        = Unit.Percent,
                            Value       = asnItemsLookup["Humidity"].Value.ToString()
                        };
                        output.Channels.Add(channel);
                    }
                }

                // Temperature
                // TODO - This is untested code
                tempStr = asnItemsLookup["Temperature"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null" && tempStr != "SNMP No-Such-Instance")
                    {
                        var temp = Convert.ToInt32(tempStr); // / 10;
                        //temp = (temp - 32) * 5 / 9; // (°F − 32) × 5/9 = °C
                        channel = new Channel
                        {
                            Description = "Temperature",
                            Unit        = Unit.Temperature,
                            Value       = temp.ToString()
                        };
                        output.Channels.Add(channel);
                    }
                }

                // Alarms Present
                var alarmsPresent = asnItemsLookup["Alarms Present"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    var alarmsPresentWarning = "0";
                    if (alarmsPresent != "0")
                    {
                        alarmsPresentWarning = "1";
                    }
                    channel = new Channel
                    {
                        Description = "# Alarms Present",
                        Unit        = Unit.Count,
                        Value       = alarmsPresent,
                        Warning     = alarmsPresentWarning
                    };
                    output.Channels.Add(channel);
                }

                // Test Results Summary
                var testResult        = asnItemsLookup["Test Result Summary"].Value.ToString().Trim();
                var testResultWarning = "0";
                switch (testResult)
                {
                case "1":
                    testResult = "donePass";
                    break;

                case "2":
                    testResult        = "doneWarning";
                    globalMessage     = "[Test Warning]";
                    testResultWarning = "1";
                    break;

                case "3":
                    testResult        = "doneError";
                    globalMessage     = "[Test Error]";
                    testResultWarning = "1";
                    break;

                case "4":
                    testResult        = "aborted";
                    globalMessage     = "[Test Aborted]";
                    testResultWarning = "1";
                    break;

                case "5":
                    testResult    = "inProgress";
                    globalMessage = "[Test In Progress]";
                    break;

                case "6":
                    testResult        = "noTestsInitiated";
                    globalMessage     = "[Test Never Initiated]";
                    testResultWarning = "1";
                    break;

                default:
                    testResult        = "unknown";
                    globalMessage     = "[Test Result Unknown]";
                    testResultWarning = "1";
                    break;
                }
                channel = new Channel
                {
                    Description = "UPS Test Result",
                    Unit        = Unit.Custom,
                    CustomUnit  = "Result",
                    Value       = testResult,
                    Warning     = testResultWarning,
                };
                output.Channels.Add(channel);

                // Last Test Date
                var timeSinceBoot         = (TimeTicks)asnItemsLookup["Up Time"].Value;
                var timeSinceTest         = (TimeTicks)asnItemsLookup["Last Test Up Time"].Value;
                var relativeTimeSinceTest = timeSinceBoot.Milliseconds - timeSinceTest.Milliseconds;
                var lastTestDate          = DateTime.Now - TimeSpan.FromMilliseconds(relativeTimeSinceTest);

                var daysSinceBatteryTest = Convert.ToInt16((DateTime.Now - lastTestDate).TotalDays);
                channel = new Channel
                {
                    Description         = "Days Since UPS Test",
                    Unit                = Unit.Custom,
                    CustomUnit          = "Days",
                    LimitErrorMessage   = "UPS Test Overdue",
                    LimitWarningMessage = "UPS Test Required",
                    LimitMaxWarning     = TestWarningDays.ToString(),
                    LimitMaxError       = TestErrorDays.ToString(),
                    LimitMode           = "1",
                    Value               = daysSinceBatteryTest.ToString()
                };
                output.Channels.Add(channel);

                if (!string.IsNullOrEmpty(globalMessage))
                {
                    message += " " + globalMessage;
                }
                output.Text = message;
                output.WriteOutput();
            }
            else
            {
                Error.WriteOutput("No Results Received from " + credentials.Host + " using community " + credentials.Community);
            }
        }
示例#30
0
        /// <summary>
        /// 同步Get操作
        /// </summary>
        /// <param name="lmtPdu"></param>
        /// <param name="requestId"></param>
        /// <param name="strIpAddr"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public int SnmpGetSync(CDTLmtbPdu lmtPdu, out long requestId, string strIpAddr, long timeOut)
        {
            requestId = 0;

            Log.Debug("========== SnmpGetSync() Start ==========");
            string msg = string.Format("pars: lmtPdu={0}, requestId={1}, strIpAddr={2}, timeOut={3}"
                                       , lmtPdu, requestId, strIpAddr, timeOut);

            Log.Debug(msg);

            if (string.IsNullOrEmpty(strIpAddr))
            {
                Log.Error("strIpAddr is null");
                return(-1);
            }
            if (lmtPdu == null)
            {
                Log.Error("参数lmtPdu为空");
                return(-1);
            }

            // TODO: 根据基站ip获取Lmtor信息
            //LMTORINFO* pLmtorInfo = CDTAppStatusInfo::GetInstance()->GetLmtorInfo(remoteIpAddr);

            SnmpHelper snmp = m_SnmpSync;

            if (null == snmp)
            {
                msg = string.Format("基站[{0}]的snmp连接不存在,无法下发snmp命令");
                Log.Error(msg);
                return(-1);
            }

            /*
             * List<string> vbList = new List<string>();
             *
             * int vbCount = lmtPdu.VbCount();
             *
             * for (int i = 0; i < vbCount; i++)
             * {
             *  CDTLmtbVb lmtVb =  lmtPdu.GetVbByIndexEx(i);
             *  string oid = lmtVb.get_Oid();
             *  vbList.Add(oid);
             * }
             */

            // SnmpV2Packet result = snmp.GetRequest(vbList);

            Pdu  pdu;
            bool rs = LmtPdu2SnmpPdu(out pdu, lmtPdu, strIpAddr);

            if (!rs)
            {
                Log.Error("LmtPdu2SnmpPdu()转换错误");
                return(-1);
            }

            SnmpV2Packet result = snmp.GetRequest(pdu);

            if (result == null)
            {
                Log.Error("SNMP request error, response is null.");
                return(-1);
            }
            requestId = result.Pdu.RequestId;

            rs = SnmpPdu2LmtPdu(result, snmp.m_target, lmtPdu, 0, false);


            return(0);
        }