コード例 #1
0
ファイル: SnmpCommands.cs プロジェクト: onixion/MAD
        private string SendRequests(UdpTarget target, SecureAgentParameters param)
        {
            try
            {
                SnmpV3Packet indexResult = (SnmpV3Packet)target.Request(_index, param);
                SnmpV3Packet descrResult = (SnmpV3Packet)target.Request(_descr, param);
                SnmpV3Packet typeResult  = (SnmpV3Packet)target.Request(_type, param);

                if (indexResult.ScopedPdu.ErrorStatus != 0 || descrResult.ScopedPdu.ErrorStatus != 0 || typeResult.ScopedPdu.ErrorStatus != 0)
                {
                    Logger.Log("SNMP Request Error", Logger.MessageType.ERROR);
                    return("<color><red>ERROR: packet error status = " + indexResult.ScopedPdu.ErrorStatus.ToString() + " and not ZERO");
                }
                else
                {
                    for (int i = 0; i < indexResult.ScopedPdu.VbCount; i++)
                    {
                        _output += "Interface " + indexResult.ScopedPdu.VbList[i].Value.ToString() + ": Type " + typeResult.ScopedPdu.VbList[i].Value.ToString() + " -> " + descrResult.ScopedPdu.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");
            }
        }
コード例 #2
0
        /// <summary>
        /// Отправляет SNMP запрос на IP адрес, возвращает ответ.
        /// </summary>
        /// <param name="ipAddress">IP адрес</param>
        /// <returns>Ответ</returns>
        private SnmpV1Packet SendRequest(string ipAddress)
        {
            // Параметры запроса.
            SnmpV1Packet result;
            var          community = new OctetString("public");
            var          param     = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver1
            };
            var agent  = new IpAddress(ipAddress);
            var target = new UdpTarget((IPAddress)agent, 161, 450, 1);
            var pdu    = new Pdu(PduType.Get);

            // Oid сетевого имени устройства.
            pdu.VbList.Add("1.3.6.1.2.1.1.5.0");
            // Oid модели.
            pdu.VbList.Add("1.3.6.1.2.1.25.3.2.1.3.1");
            // Oid серийного номера.
            pdu.VbList.Add("1.3.6.1.2.1.43.5.1.1.17.1");
            // Отправка запроса.
            result = (SnmpV1Packet)target.Request(pdu, param);
            // Ошибок нет.
            if (result.Pdu.ErrorStatus == 0)
            {
                // Если сетевое имя пустое.
                if (string.IsNullOrWhiteSpace(result.Pdu.VbList[0].Value.ToString()))
                {
                    var kyoceraPdu = new Pdu(PduType.Get);
                    // Oid сетевого имени устройства.
                    kyoceraPdu.VbList.Add("1.3.6.1.4.1.1347.40.10.1.1.5.1");
                    // Oid модели.
                    kyoceraPdu.VbList.Add("1.3.6.1.2.1.25.3.2.1.3.1");
                    // Oid серийного номера.
                    kyoceraPdu.VbList.Add("1.3.6.1.2.1.43.5.1.1.17.1");
                    result = (SnmpV1Packet)target.Request(kyoceraPdu, param);
                }
            }
            // При ошибке запросить с параметрами для зебры.
            else
            {
                var zebraPdu = new Pdu(PduType.Get);
                // Oid сетевого имени устройства.
                zebraPdu.VbList.Add("1.3.6.1.2.1.1.5.0");
                // Oid модели.
                zebraPdu.VbList.Add("1.3.6.1.2.1.25.3.2.1.3.1");
                // Oid серийного номера.
                zebraPdu.VbList.Add("1.3.6.1.4.1.10642.1.9.0");
                result = (SnmpV1Packet)target.Request(zebraPdu, param);
            }
            target.Close();
            return(result);
        }
コード例 #3
0
        private static string[] SNMPget(string ip, string[] oid)
        {
            var output = new string[oid.Length];
            var agent  = new IpAddress(ip);
            var pdu    = new Pdu(PduType.Get);

            foreach (var item in oid)
            {
                pdu.VbList.Add(item);
            }
            using (var target = new UdpTarget((IPAddress)agent, 161, 512, 1))
            {
                try
                {
                    var result2 = (SnmpV2Packet)target.Request(pdu, new AgentParameters(SnmpVersion.Ver2, new OctetString("public")));
                    for (int i = 0; i < result2.Pdu.VbList.Count; i++)
                    {
                        if (oid[i] == "1.3.6.1.2.1.25.3.5.1.2.1")
                        {
                            output[i] = ((OctetString)(result2.Pdu.VbList[i].Value)).ToArray()[0].ToString();
                        }
                        else
                        {
                            output[i] = result2.Pdu.VbList[i].Value.ToString();
                        }
                    }
                }
                catch (Exception)
                {
                    var result1 = (SnmpV1Packet)target.Request(pdu, new AgentParameters(SnmpVersion.Ver1, new OctetString("public")));
                    for (int i = 0; i < result1.Pdu.VbList.Count; i++)
                    {
                        if (oid[i] == "1.3.6.1.2.1.25.3.5.1.2.1")
                        {
                            //{
                            output[i] = ((OctetString)(result1.Pdu.VbList[i].Value)).ToArray()[0].ToString();
                        }

                        /*if (output[i] == "\0" || output[i] == "Null" || output[i] == "" || output[i] == "00 00")
                         *  output[i] = "0";*/
                        //}
                        else
                        {
                            output[i] = result1.Pdu.VbList[i].Value.ToString();
                        }
                    }
                }
                return(output);
            }
        }
コード例 #4
0
        public SnmpV1Packet GetRequest(string OID)
        {
            this.param.Version = SnmpVersion.Ver1;
            this.pdu           = new Pdu(PduType.Get);
            this.pdu.VbList.Add(OID);
            result = (SnmpV1Packet)target.Request(pdu, param);

            OidNumber = result.Pdu.VbList[0].Oid.ToString();
            type      = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);
            value     = result.Pdu.VbList[0].Value.ToString();
            ipPort    = address + ":161";

            return(result);
        }
コード例 #5
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());
        }
コード例 #6
0
ファイル: Counter.cs プロジェクト: Callightman/AutoCounter
        private string GetCounters(string ip, string query)
        {
            try
            {
                OctetString     community = new OctetString("public");
                AgentParameters param     = new AgentParameters(community);
                param.Version = SnmpVersion.Ver1;
                IpAddress agent  = new IpAddress(ip);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 3000, 1);

                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add(query);
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result != null)
                {
                    return(result.Pdu.VbList[0].Value.ToString());
                }

                else
                {
                    return("-");
                }
            }
            catch
            {
                return("-");
            }
        }
コード例 #7
0
ファイル: SnmpCommands.cs プロジェクト: onixion/MAD
        private uint ParameterCountRequest(SecureAgentParameters param, UdpTarget target)
        {
            Oid deviceNr = new Oid(_ifNr);
            Pdu devices  = new Pdu(PduType.Get);

            devices.VbList.Add(deviceNr);

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

                if (devicesResult.ScopedPdu.ErrorStatus != 0)
                {
                    return(0);
                }
                else
                {
                    return(Convert.ToUInt32(devicesResult.ScopedPdu.VbList[0].Value.ToString()));
                }
            }
            catch (Exception)
            {
                return(0);
            }
        }
コード例 #8
0
        private void ExecuteRequest(UdpTarget target, SecureAgentParameters 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
            {
                SnmpV3Packet nameResult = (SnmpV3Packet)target.Request(_namePacket, param);

                if (nameResult.ScopedPdu.VbList[0].Value.ToString().ToLowerInvariant() == System.Environment.MachineName.ToLowerInvariant())
                {
                    Logger.Log("SNMP Service seems to work", Logger.MessageType.INFORM);
                    outp.outState = JobOutput.OutState.Success;
                }
                else
                {
                    Logger.Log("SNMP Service seems to be dead", Logger.MessageType.ERROR);
                    outp.outState = JobOutput.OutState.Failed;
                }
            }
            catch (Exception)
            {
                Logger.Log("SNMP Service seems to be dead", Logger.MessageType.ERROR);
                outp.outState = JobOutput.OutState.Exception;
            }
        }
コード例 #9
0
        private void sendSetCommand(string OID, string parameters)
        {
            //tmrRequest.Enabled = false;

            UdpTarget target = new UdpTarget((IPAddress) new IpAddress(txtCurrentIP.Text));
            Pdu       pdu    = new Pdu(PduType.Set);

            pdu.VbList.Add(new Oid(OID), new OctetString(parameters));

            AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString("private"));
            // Response packet
            SnmpV2Packet response;

            try
            {
                // Send request and wait for response
                response = target.Request(pdu, aparam) as SnmpV2Packet;
            }
            catch (Exception ex)
            {
                WriteMessage(ex.ToString());
                target.Close();
                return;
            }

            //tmrRequest.Enabled = true;
        }
コード例 #10
0
ファイル: Form1.cs プロジェクト: zdatou/DotNet_Snmp
        private void Snmp_Get(string ip, string oid, string comm)
        {
            OctetString     community = new OctetString(comm);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            IpAddress agent  = new IpAddress(ip);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            Pdu       pdu    = new Pdu(PduType.Get);

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

            if (result != null)
            {
                if (result.Pdu.ErrorStatus != 0)
                {
                    this.txtTest.Text += string.Format("Error in SNMP reply. Error {0} index {1} \r\n", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                }
                else
                {
                    int index = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[index].Cells[0].Value = "hello";
                    this.dataGridView1.Rows[index].Cells[1].Value = result.Pdu.VbList[0].Oid.ToString();
                    this.dataGridView1.Rows[index].Cells[2].Value = SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type);
                    this.dataGridView1.Rows[index].Cells[3].Value = result.Pdu.VbList[0].Value.ToString();
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// 带有异步回调的GetResponse;
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="PduList"></param>
        /// <param name="Community"></param>
        /// <param name="IpAddr"></param>
        public override void GetRequest(AsyncCallback callback, List <string> PduList, string Community, string IpAddr)
        {
            // 当确认全部获取SNMP数据后,调用callback回调;
            SnmpHelperResult            res       = new SnmpHelperResult();
            OctetString                 community = new OctetString(Community);
            AgentParameters             param     = new AgentParameters(community);
            Dictionary <string, string> rest      = new Dictionary <string, string>();

            param.Version = SnmpVersion.Ver2;

            // 创建代理(基站);
            UdpTarget target = ConnectToAgent(Community, IpAddr);

            // Pdu请求形式Get;
            Pdu pdu = new Pdu(PduType.Get);

            foreach (string pdulist in PduList)
            {
                pdu.VbList.Add(pdulist);
            }

            Task tsk = Task.Factory.StartNew(() => {
                // 接收结果;
                m_Result = (SnmpV2Packet)target.Request(pdu, param);

                if (m_Result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (m_Result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          m_Result.Pdu.ErrorStatus,
                                          m_Result.Pdu.ErrorIndex);

                        rest.Add(m_Result.Pdu.ErrorIndex.ToString(), m_Result.Pdu.ErrorStatus.ToString());
                        res.SetSNMPReslut(rest);
                        Thread.Sleep(3111);
                        callback(res);
                    }
                    else
                    {
                        for (int i = 0; i < m_Result.Pdu.VbCount; i++)
                        {
                            rest.Add(m_Result.Pdu.VbList[i].Oid.ToString(), m_Result.Pdu.VbList[i].Value.ToString());
                            res.SetSNMPReslut(rest);
                            Thread.Sleep(3111);
                            callback(res);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }

                target.Close();
            });
        }
コード例 #12
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);
        }
コード例 #13
0
        /*
         * Fetching informations from Printer.
         */
        private void setCheckerPrinter(AgentParameters param, UdpTarget target, string s)
        {
            try
            {
                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add(s);

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

                printer.uniquePrinterNumber = result.Pdu.VbList[0].Value.ToString();

                printer.setBilling(getBilling(param, target, OID_Billing));
                addMessagesToList(param, target);
                printer.setStatus(getStatus(param, target, OID_Status));

                //Console.WriteLine(getMessages(param, target, OID_Message5).Equals("Null"));
                //printer.setMessage(getMessages(param,target,OID_Message1));
                //Console.WriteLine(printer.getName() + " message: " + getMessages(param, target, OID_Message3));
            }
            catch (SnmpException e)
            {
                printer.setBilling("0");
                Console.WriteLine(e.Message);
            }
        }
コード例 #14
0
        /**
         *  Preparing informations for labeling.
         */
        private string getBilling(AgentParameters param, UdpTarget target, string OID_Billing)
        {
            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.Get);

            pdu.VbList.Add(OID_Billing);

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

            long value = 0;

            try
            {
                value = long.Parse(result.Pdu.VbList[0].Value.ToString());
            }
            catch (OverflowException e)
            {
                Console.WriteLine(e.Message);
            }

            printer.setBilling(value.ToString("#,#", CultureInfo.InvariantCulture));

            return(value.ToString("#,#", CultureInfo.InvariantCulture));
        }
コード例 #15
0
 public bool GetPortBInstalled(UdpTarget target)
 {
     try
     {
         var pdu = Pdu.GetPdu(new VbCollection {
             CreateVb(conv4000ConvBInstalled.Default.oid)
         });
         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);
         }
         if (response.Pdu.ErrorStatus != 0)
         {
             return(false);
         }
         return((Integer32)response.Pdu.VbList[0].Value == 1 ? true : false);
     }
     catch (Exception ex)
     {
         _logger.WriteMessage(ex.Message, DebugLevel.ERROR);
         return(false);
     }
 }
コード例 #16
0
ファイル: SNMP.cs プロジェクト: faraanh/miniSNMP
        private void GetMore(int n)
        {
            OctetString     community = new OctetString(txtConStr.Text);
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            try
            {
                IpAddress agent  = new IpAddress(txtIPAgent.Text);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Pdu       pdu    = new Pdu(PduType.Get);
                string[]  row;
                for (int i = 1; i <= n; i++)
                {
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.3." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.5." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.10." + i.ToString());
                    pdu.VbList.Add("1.3.6.1.2.1.2.2.1.16." + i.ToString());
                    SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                    row = new string[] { i.ToString(), result.Pdu.VbList[0].Value.ToString(), GetType(int.Parse(result.Pdu.VbList[1].Value.ToString())), result.Pdu.VbList[2].Value.ToString(), result.Pdu.VbList[3].Value.ToString(), result.Pdu.VbList[4].Value.ToString() };
                    dgvList.Rows.Add(row);
                    pdu.Reset();
                }
                target.Close();
            }
            catch (Exception ex)
            {
                rtbGuiGet.Text = "Đã xảy ra lỗi: " + ex.Message.ToString();
            }
        }
コード例 #17
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);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: wellbin-li/CSharp-Examples
        public 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 = (int)SnmpVersion.Ver1;
            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请求
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

            get = result.Pdu.VbList[0].Value.ToString();

            return(get);
        }
コード例 #19
0
        }//将对应id的条目的值设置为data

        private void GetPrinterResponse(object input_id)
        {
            string id     = input_id.ToString();
            string ipaddr = null;

            for (int i = 0; i < Common.dt_printer.Rows.Count; i++)
            {
                string tmp = Common.dt_printer.Rows[i]["Id"].ToString();
                if (tmp == (string)id)
                {
                    ipaddr = Common.dt_printer.Rows[i]["dev_ip"].ToString();
                }
            }
            int             feq       = Common.getfequency((string)id);
            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver1;
            IpAddress agent  = new IpAddress(ipaddr);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            Pdu       pdu    = new Pdu(PduType.Get);

            pdu.VbList.Add("1.3.6.1.2.1.43.11.1.1.9.1.1");
            for (; ;)
            {
                if (canceltokensource.IsCancellationRequested == true)
                {
                    Common.writetologfrm(string.Format("打印机 设备ID:{1} 线程{0}终止", Thread.CurrentThread.ManagedThreadId, id.ToString()));
                    target.Dispose();
                    this.Close();
                    break;//若收到cancellationToken消息则取消此线程
                }
                try
                {
                    SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                    if (result != null)
                    {
                        if (result.Pdu.ErrorStatus != 0)
                        {
                            Common.writetologfrm(string.Format("打印机 ID:{0} 获取信息异常码{1}在{2}上", (string)id, result.Pdu.ErrorStatus, result.Pdu.ErrorIndex));
                        }
                        else
                        {
                            int i = Convert.ToInt32(result.Pdu.VbList[0].Value.ToString());

                            this.Invoke(new MethodInvoker(() => { show_data(id, i); }));
                        }
                    }
                    else
                    {
                        Common.writetologfrm(string.Format("打印机 ID:{0} 未收到回复", (string)id));
                    }
                }
                catch {
                    Common.writetologfrm(string.Format("打印机 ID:{0} 获取信息异常", (string)id));
                }
                Thread.Sleep(Common.getfequency((string)id));
            }
            //target.Dispose();
        }//Printer线程工作内容
コード例 #20
0
ファイル: SnmpClient.cs プロジェクト: Fearvel/openMPS
        /// <summary>
        /// Gets the specific values of an OID
        /// </summary>
        /// <param name="ip">The ip.</param>
        /// <param name="oid">The oid.</param>
        /// <returns></returns>
        public static string GetOidValue(string ip, string oid)
        {
            var oidValue = "";

            try
            {
                if (oid.Length > 0)
                {
                    var community = new OctetString("public");
                    var param     = new AgentParameters(community)
                    {
                        Version = SnmpVersion.Ver1
                    };
                    var agent  = new IpAddress(ip);
                    var target = new UdpTarget((IPAddress)agent, 161, 5000, 1);
                    var pdu    = new Pdu(PduType.Get);
                    pdu.VbList.Add(oid);
                    var result = (SnmpV1Packet)target.Request(pdu, param);
                    if (result?.Pdu.ErrorStatus == 0)
                    {
                        oidValue = result.Pdu.VbList[0].Value.ToString();
                    }
                    target.Close();
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(oidValue);
        }
コード例 #21
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);
            }
        }
コード例 #22
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.");
            }
        }
コード例 #23
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);
        }
コード例 #24
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();
            }
        }
コード例 #25
0
        public DownConverterHandler()
        {
            // Start status polling
            _worker = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            _worker.DoWork += (sender, args) =>
            {
                var worker             = sender as BackgroundWorker;
                var lastKeepAliveCheck = DateTime.Now;
                var lastKeepAlive      = DateTime.Now;
                var status             = new DownConverterStatusEventArgs();

                while (!worker.CancellationPending)
                {
                    Thread.Sleep(100);

                    var now = DateTime.Now;

                    if ((now - lastKeepAliveCheck).TotalSeconds > 5)
                    {
                        using (var target = new UdpTarget(IPAddress.Parse(DeviceIp)))
                        {
                            try
                            {
                                var pdu    = Pdu.GetPdu(new VbCollection(new[] { new Vb(new Oid("1.3.6.1.2.1.1.1.0")) }));
                                var param  = new AgentParameters(SnmpVersion.Ver2, new OctetString("public"));
                                var result = target.Request(pdu, param) as SnmpV2Packet;
                                if (result != null && result.Pdu.ErrorStatus == 0)
                                {
                                    lastKeepAlive = DateTime.Now;
                                    if (!status.IsAlive)
                                    {
                                        status.IsAlive = true;
                                        UpdateDeviceStatus(status);
                                    }
                                }
                            }
                            catch { }
                        }

                        lastKeepAliveCheck = now;
                    }

                    if ((now - lastKeepAlive).TotalSeconds > 30)
                    {
                        if (status.IsAlive)
                        {
                            status.IsAlive = false;
                            UpdateDeviceStatus(status);
                        }
                    }
                }
            };
            _worker.RunWorkerAsync();
        }
コード例 #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());
        }
コード例 #27
0
 //多執行緒檢察linux
 private void CheckLinuxDiskThread(object obj)
 {
     //0 = TargetName, 1= TargetIP ,2=TargetAlert ,3=TargetSpaceLog ,4=id ,5=TargetWarning
     string[] Askitem = new string[6];
     Askitem = (string[])obj;
     try
     {
         // SNMP community name
         OctetString     community = new OctetString("public");
         AgentParameters param     = new AgentParameters(community);
         param.Version = SnmpVersion.Ver1;
         IpAddress agent = new IpAddress(Askitem[1]);//TargetIP
         // Construct target
         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.4.1.2021.9.1.2.1"); //代號
         pdu.VbList.Add(".1.3.6.1.4.1.2021.9.1.6.1"); //總空間
         pdu.VbList.Add(".1.3.6.1.4.1.2021.9.1.8.1"); //已用空間
         // Make SNMP request
         SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
         //取得 總空間kb 已用空間kb 分割區帶號
         int    AllKB  = int.Parse(result.Pdu.VbList[1].Value.ToString());
         int    UseKB  = int.Parse(result.Pdu.VbList[2].Value.ToString());
         int    FreeKB = AllKB - UseKB;
         int    AllMB  = AllKB / 1024;
         int    FreeMB = FreeKB / 1024;
         int    AllGB  = AllMB / 1024;
         int    FreeGB = FreeMB / 1024;
         string ID     = result.Pdu.VbList[0].Value.ToString();
         //委派傳出
         string[] text = new string[10];
         text[0] = Askitem[0];        //名稱
         text[1] = ID;                //代號
         text[2] = AllMB.ToString();  //總空間mb
         text[3] = AllGB.ToString();  //總空間gb
         text[4] = FreeMB.ToString(); //剩餘mb
         text[5] = FreeGB.ToString(); //剩餘gb
         text[6] = Askitem[2];        //警戒值
         text[7] = "Linux";           //檢察linux
         text[8] = Askitem[4];        //WindowsTargetID
         text[9] = Askitem[5];        //TargetWaning
         this.Invoke(new D_AddAlreadyGridView(AddAlreadyGridView), new object[] { text });
         //如果低於警戒值
         if (FreeMB <= Convert.ToInt32(Askitem[2]))
         {
             this.Invoke(new D_AddAlertGridView(AddAlertGridView), new object[] { text });
         }
     }
     catch (Exception x)
     {
         this.Invoke(new D_AddErrorList(AddErrorList), Askitem[0] + " >>> " + x.Message.ToString());
     }
     this.Invoke(new D_AddProgress(AddProgress), null);
 }
コード例 #28
0
        public string GetHersteller()
        {
            // SNMP community name
            OctetString community = new OctetString("public");
            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);

            // Set SNMP version to 1 (or 2)
            param.Version = SnmpVersion.Ver1;
            // 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(Ip);

            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 250, 1);

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

            pdu.VbList.Add(".1.3.6.1.2.1.25.3.2.1.3.1"); //sysDescr

            // Make SNMP request
            try
            {
                SnmpV1Packet result = (SnmpV1Packet)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("Error in SNMP reply.");
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        target.Close();
                        return(result.Pdu.VbList[0].Value.ToString());
                    }
                }
                else
                {
                    target.Close();
                    return("No response received from SNMP agent.");
                }
            }
            catch { target.Close(); return("Fehler"); }
        }
コード例 #29
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);
            }
        }
コード例 #30
0
        private void RunSetCommands()
        {
            // This runs all the time and waits for SET requesets to be appended to _commands.
            _sender = new BackgroundWorker {
                WorkerSupportsCancellation = true, WorkerReportsProgress = true
            };
            _sender.DoWork += (sender, e) =>
            {
                _logger.WriteMessage("Sending worker started", DebugLevel.DEBUG);
                var worker = sender as BackgroundWorker;
                while (!worker.CancellationPending)
                {
                    try
                    {
                        using (var target = new UdpTarget(HostName, Port, Timeout, Retry))
                        {
                            while (_commands.TryDequeue(out Pdu[] pdus))
                            {
                                foreach (var pdu in pdus)
                                {
                                    try
                                    {
                                        var param  = new AgentParameters(SnmpVersion.Ver2, new OctetString(WriteCommunity));
                                        var result = target.Request(pdu, param);
                                        if (result == null)
                                        {
                                            _logger.WriteMessage("Send command result is null", DebugLevel.ERROR);
                                        }
                                        else if (result.Pdu.ErrorStatus != 0)
                                        {
                                            _logger.WriteMessage(String.Format("{0} raised error number: {1} - {2}", result.Pdu.RequestId, result.Pdu.ErrorIndex, ((PduErrorStatus)result.Pdu.ErrorIndex).ToString()), DebugLevel.ERROR);
                                        }
                                        else
                                        {
                                            worker.ReportProgress(0);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.WriteMessage(ex.Message, DebugLevel.ERROR);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.WriteMessage(ex.Message, DebugLevel.ERROR);
                    }
                }
            };

            _sender.RunWorkerAsync();
        }
コード例 #31
0
ファイル: SharpWalk.cs プロジェクト: odnanref/snrviewer
        static void remoteCall(string[] args)
        {
            // SNMP community name
            OctetString community = new OctetString("public");

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            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");

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

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid("1.3.6.1.2.1.2.2.1.2"); // 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))
                            {
                                Console.WriteLine("{0} ({1}): {2}",
                                    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();
        }