Example #1
0
        private void GetSNMPValues(IList <OidRow> oidTable)
        {
            // SNMP community name
            OctetString communityObj = new OctetString(community);

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

            param.Version = SnmpVersion.Ver2;

            IpAddress agent = new IpAddress(ipAddress);

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

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

            foreach (OidRow or in oidTable)
            {
                pdu.VbList.Add(or.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
                    Errors.Add($"Error in SNMP reply. Error {result.Pdu.ErrorStatus} index {result.Pdu.ErrorIndex}. ");
                }
                else
                {
                    DateTime date = DateTime.Now;
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    foreach (OidRow or in oidTable)
                    {
                        or.PreviousResult = or.CurrentResult;
                        or.CurrentResult  = result.Pdu.VbList[oidTable.IndexOf(or)].Value.ToString();
                        or.CurrentDate    = date;

                        or.Results.Add(new OidResult()
                        {
                            RequestDate = date,
                            Value       = or.CurrentResult
                        });
                    }
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();
        }
Example #2
0
        public static void GetTable(string host, string community, string oid, DataGridView table)
        {
            string type;

            Program.mibObjectsTypes.TryGetValue(Program.mibObjects.FirstOrDefault(x => x.Value == oid).Key, out type);
            if (type != "T")
            {
                MessageBox.Show("Selected position is not a table!");
                return;
            }

            table.Rows.Clear();
            table.Refresh();

            Dictionary <String, Dictionary <uint, AsnType> > result = new Dictionary <String, Dictionary <uint, AsnType> >();
            List <uint>   tableColumns = new List <uint>();
            List <string> tableRows    = new List <string>();

            AgentParameters param;
            IpAddress       peer;

            try
            {
                param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
                peer  = new IpAddress(host);
            }
            catch (Exception e)
            {
                MessageBox.Show("Invalid IP/port or community settings");
                return;
            }


            if (!peer.Valid)
            {
                MessageBox.Show("Unable to resolve name or error in address for peer: {0}", host);
                return;
            }

            UdpTarget target   = new UdpTarget((System.Net.IPAddress)peer);
            Oid       startOid = new Oid(oid);

            startOid.Add(1);
            Pdu           getNextPdu  = Pdu.GetNextPdu();
            Oid           curOid      = (Oid)startOid.Clone();
            List <string> columnNames = new List <string>();

            string searchOid = "." + startOid.ToString();

            foreach (KeyValuePair <string, string> kvp in Program.mibObjects)
            {
                if (kvp.Value.Contains(searchOid) && !kvp.Value.Equals(searchOid))
                {
                    columnNames.Add(kvp.Key);
                }
            }

            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(getNextPdu, param);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Request failed: {0}", ex.Message);
                    target.Close();
                    return;
                }

                if (res.Pdu.ErrorStatus != 0)
                {
                    MessageBox.Show("SNMP agent returned error " + res.Pdu.ErrorStatus + " for request Vb index " + res.Pdu.ErrorIndex);
                    target.Close();
                    return;
                }

                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();
                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                        uint[] instance  = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint   column  = childOids[0];
                        if (!tableColumns.Contains(column))
                        {
                            tableColumns.Add(column);
                        }
                        if (result.ContainsKey(strInst))
                        {
                            result[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            result[strInst]         = new Dictionary <uint, AsnType>();
                            result[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (startOid.IsRootOf(curOid))
                {
                    getNextPdu.VbList.Clear();
                    getNextPdu.VbList.Add(curOid);
                }
            }
            target.Close();

            if (result.Count <= 0)
            {
                MessageBox.Show("No results returned.");
            }
            else
            {
                table.ColumnCount     = tableColumns.Count + 1;
                table.Columns[0].Name = "Instance";
                for (int i = 0; i < tableColumns.Count; i++)
                {
                    table.Columns[i + 1].Name = columnNames[i];
                    //table.Columns[i + 1].Name = "Column id " + tableColumns[i];
                }
                foreach (KeyValuePair <string, Dictionary <uint, AsnType> > kvp in result)
                {
                    tableRows.Add(kvp.Key);
                    foreach (uint column in tableColumns)
                    {
                        if (kvp.Value.ContainsKey(column))
                        {
                            tableRows.Add(kvp.Value[column].ToString());
                        }
                        else
                        {
                            tableRows.Add("");
                        }
                    }
                    table.Rows.Add(tableRows.ToArray());
                    tableRows.Clear();
                }
            }
        }
Example #3
0
        /// <summary>
        /// 由表中一列的OID来获取整列的值集合,若出错,返回null,一般用来获取表格的索引列
        /// </summary>
        /// <param name="agentIP">目标IP地址</param>
        /// <param name="_rootOid">此列的OID</param>
        /// <param name="errorMessage">输出错误信息,若没有错误,返回空字符串</param>
        /// <returns>返回字符串集合,之后自行根据此列类型进行转换,若出错,返回null</returns>
        public static List <string> GetSingleColumnListFromTable(IpAddress agentIP, Oid rootOid, out string errorMessage)
        {
            OctetString     community = new OctetString(App.snmpCommunity);
            AgentParameters param     = new AgentParameters(community);

            param.DisableReplySourceCheck = !App.snmpCheckSrcFlag;
            // 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, App.snmpPort, App.snmpTimeout, App.snmpRetry);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            //Oid rootOid = rootOid;

            // 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;

            List <string> resultList = new List <string>();

            // 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 = null;
                try
                {
                    result = (SnmpV2Packet)target.Request(pdu, param);
                }
                catch (Exception ex)
                {
                    errorMessage = "获取SNMP应答出现错误;" + ex.Message;
                    target.Close();
                    return(null);
                }
                // 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
                        lastOid      = null;
                        errorMessage = string.Format("SNMP应答数据包中有错误。 Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                        return(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))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                                resultList.Add(v.Value.ToString());
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                                break; // 每个数据包获取5个值,一旦有一个不是这一列的数据,后面的应该都不是了
                            }
                        }
                    }
                }
                else
                {
                    errorMessage = "指定网管代理未返回有效信息";
                    return(null);
                }
            }
            target.Close();
            errorMessage = "";
            return(resultList);
        }
Example #4
0
        /// <summary>
        /// Funkcja zwracająca , zaczynając od obiektu o oid podanym w argumencie.
        /// </summary>
        /// <param name="version"></param>
        /// <param name="startOid"></param>
        /// <returns></returns>
        public Dictionary <String, Dictionary <uint, AsnType> > GetTableRequest(SnmpVersion version, string _startOid)
        {
            Dictionary <String, Dictionary <uint, AsnType> > resultDictionary = new Dictionary <String, Dictionary <uint, AsnType> >();

            //To jest OID tabeli na wejściu funkcji
            Oid startOid = new Oid(_startOid);

            /*
             * // Not every row has a value for every column so keep track of all columns available in the table
             * List<uint> tableColumns = new List<uint>();
             *
             * //Każda tabela OID ma na końcu .1 dla wpisu OID, trzeba go dodać do tabeli
             * startOid.Add(1);
             *
             * //Przygotowanie PDU do zapytania
             * Pdu pdu = new Pdu(PduType.GetNext);
             *
             * //Dodanie startOid do VarBindList PDU
             * pdu.VbList.Add(startOid);
             */

            Oid currentOid = (Oid)startOid.Clone();

            AgentParameters param = new AgentParameters(
                version, new OctetString(snmp.Community));

            //Dopoki nie osiagniemy konca tabeli
            while (startOid.IsRootOf(currentOid))
            {
                SnmpPacket result = null;

                try
                {
                    result = this.GetNextRequest(SnmpVersion.Ver2, currentOid.ToString(), this.snmp.PeerIP);
                }
                catch (Exception e)
                {
                    Console.WriteLine("GetTableRequest(): request failed. " + e.Message);
                    return(null);
                }

                if (result.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP Agent returned error: " + result.Pdu.ErrorStatus +
                                      " for request with Vb of index: " + result.Pdu.ErrorIndex);
                    return(null);
                }

                foreach (Vb v in result.Pdu.VbList)
                {
                    currentOid = (Oid)v.Oid.Clone();

                    //upewniamy sie ze jestesmy w tabeli
                    if (startOid.IsRootOf(v.Oid))
                    {
                        //Otrzymanie ID childa z OID
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);

                        // Get the value instance and converted it to a dotted decimal
                        //  string to use as key in result dictionary
                        uint[] instance = new uint[childOids.Length - 1];

                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);

                        String strInst = InstanceToString(instance);
                        // Column id is the first value past <table oid>.entry in the response OID

                        uint column = childOids[0];

                        if (resultDictionary.ContainsKey(strInst))
                        {
                            resultDictionary[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            resultDictionary[strInst]         = new Dictionary <uint, AsnType>();
                            resultDictionary[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        // We've reached the end of the table. No point continuing the loop
                        break;
                    }
                }
            }
            return(resultDictionary);
        }
Example #5
0
        static void Main(string[] args)
        {
            // Delete file if it exists.
            if (File.Exists(@".\\SnmpDump.txt"))
            {
                File.Delete(@".\\SnmpDump.txt");
            }
            if (args.Length != 3)
            {
                Console.WriteLine("Syntax: SnmpTable.exe <host> <community> <table oid>");
                return;
            }
            Dictionary <String, Dictionary <uint, AsnType> > result = new Dictionary <String, Dictionary <uint, AsnType> >();
            List <uint>     tableColumns = new List <uint>();
            AgentParameters param        = new AgentParameters(SnmpVersion.Ver2, new OctetString(args[1]));
            IpAddress       peer         = new IpAddress(args[0]);

            if (!peer.Valid)
            {
                Console.WriteLine("Unable to resolve name or error in address for peer: {0}", args[0]);
                return;
            }
            UdpTarget target   = new UdpTarget((IPAddress)peer);
            Oid       startOid = new Oid(args[2]);

            startOid.Add(1);
            Pdu bulkPdu = Pdu.GetBulkPdu();

            bulkPdu.VbList.Add(startOid);
            bulkPdu.NonRepeaters   = 0;
            bulkPdu.MaxRepetitions = 100;
            Oid curOid = (Oid)startOid.Clone();

            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;
                try
                {
                    res = target.Request(bulkPdu, param);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Request failed: {0}", ex.Message);
                    target.Close();
                    return;
                }
                if (res.Version != SnmpVersion.Ver2)
                {
                    Console.WriteLine("Received wrong SNMP version response packet.");
                    target.Close();
                    return;
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP agent returned error {0} for request Vb index {1}",
                                      res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
                    target.Close();
                    return;
                }
                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();
                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);
                        uint[] instance  = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint   column  = childOids[0];
                        if (!tableColumns.Contains(column))
                        {
                            tableColumns.Add(column);
                        }
                        if (result.ContainsKey(strInst))
                        {
                            result[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            result[strInst]         = new Dictionary <uint, AsnType>();
                            result[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                if (startOid.IsRootOf(curOid))
                {
                    bulkPdu.VbList.Clear();
                    bulkPdu.VbList.Add(curOid);
                    bulkPdu.NonRepeaters   = 0;
                    bulkPdu.MaxRepetitions = 100;
                }
            }
            target.Close();
            if (result.Count <= 0)
            {
                Console.WriteLine("No results returned.\n");
            }
            else
            {
                foreach (uint column in tableColumns)
                {
                    //Console.Write("\tColumn id {0}", column);
                }
                Console.WriteLine("");
                foreach (KeyValuePair <string, Dictionary <uint, AsnType> > kvp in result)
                {
                    //Console.WriteLine("{0}", kvp.Key);
                    string Entry = "";
                    foreach (uint column in tableColumns)
                    {
                        if (kvp.Value.ContainsKey(column))
                        {
                            //Console.WriteLine("\t{0} ({1})", kvp.Value[column].ToString(),SnmpConstants.GetTypeName(kvp.Value[column].Type));
                            Entry += kvp.Value[column].ToString() + ";";
                        }
                        else
                        {
                            Console.Write("\t-");
                        }
                    }
                    using (StreamWriter sw = File.AppendText(path))
                    {
                        Console.WriteLine(Entry);
                        sw.WriteLine(Entry);
                    }
                }
            }
        }
Example #6
0
        void getSNMP(string ip, out float ValueA, out float ValueB, out string Status)
        {
            ValueA = 0;
            ValueB = 0;
            Status = "";
            // 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;

            IpAddress agent = new IpAddress(ip);

            // 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.33826.1.1.5.1.2.1");     //a
            pdu.VbList.Add("1.3.6.1.4.1.33826.1.1.5.1.2.2");     //b
            Application.DoEvents();
            // Make SNMP request
            try{
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                Application.DoEvents();
                // 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);
                        Status = "false";
                    }
                    else
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        //  MessageBox.Show(result.Pdu.VbList[0].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + ") " + result.Pdu.VbList[0].Value.ToString());
                        //   MessageBox.Show(result.Pdu.VbList[1].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type) + ") " + result.Pdu.VbList[1].Value.ToString());
                        //  MessageBox.Show(result.Pdu.VbList[2].Oid.ToString() + " (" + SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type) + ") " + result.Pdu.VbList[2].Value.ToString());
                        ValueA = float.Parse(result.Pdu.VbList[0].Value.ToString()) / 10;
                        ValueB = float.Parse(result.Pdu.VbList[1].Value.ToString()) / 10;
                        Status = "done";
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
                target.Close();
            }
            catch
            {
                Status = "false";
            }
        }
Example #7
0
        private void GetTable(String host, AgentParameters param, String tableOID, DataGridView table)
        {
            table.Rows.Clear();
            table.Refresh();
            Dictionary <String, Dictionary <uint, AsnType> > result = new Dictionary <String, Dictionary <uint, AsnType> >();
            List <uint>   tableColumns = new List <uint>();
            List <string> tableRows    = new List <string>();
            IpAddress     peer         = new IpAddress(host);

            if (!peer.Valid)
            {
                MessageBox.Show("Unable to resolve name or error in address for peer: {0}", host);
                return;
            }
            UdpTarget target   = new UdpTarget((IPAddress)peer);
            Oid       startOid = new Oid(tableOID);

            startOid.Add(1);
            Pdu nextPdu = Pdu.GetNextPdu();

            nextPdu.VbList.Add(startOid);
            Oid           curOid    = (Oid)startOid.Clone();
            List <string> colNames  = new List <string>();
            string        searchOid = "." + startOid.ToString();

            foreach (KeyValuePair <string, string> kvp in Program.MIbsList)
            {
                if (kvp.Value.Contains(searchOid) && !kvp.Value.Equals(searchOid))
                {
                    colNames.Add(kvp.Key);
                }
            }

            while (startOid.IsRootOf(curOid))
            {
                SnmpPacket res = null;

                try
                {
                    res = target.Request(nextPdu, param);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Request failed: {0}", e.Message);
                    target.Close();
                    return;
                }

                if (res.Pdu.ErrorStatus != 0)
                {
                    MessageBox.Show("SNMP agent returned error " + res.Pdu.ErrorStatus + " for request Vb index " + res.Pdu.ErrorIndex);
                    target.Close();
                    return;
                }

                foreach (Vb v in res.Pdu.VbList)
                {
                    curOid = (Oid)v.Oid.Clone();

                    if (startOid.IsRootOf(v.Oid))
                    {
                        uint[] childOids = Oid.GetChildIdentifiers(startOid, v.Oid);

                        uint[] instance = new uint[childOids.Length - 1];
                        Array.Copy(childOids, 1, instance, 0, childOids.Length - 1);
                        String strInst = InstanceToString(instance);
                        uint   column  = childOids[0];

                        if (!tableColumns.Contains(column))
                        {
                            tableColumns.Add(column);
                        }

                        if (result.ContainsKey(strInst))
                        {
                            result[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            result[strInst]         = new Dictionary <uint, AsnType>();
                            result[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (startOid.IsRootOf(curOid))
                {
                    nextPdu.VbList.Clear();
                    nextPdu.VbList.Add(curOid);
                }
            }
            target.Close();

            if (result.Count <= 0)
            {
                MessageBox.Show("No results returned.");
            }
            else
            {
                table.ColumnCount     = tableColumns.Count + 1;
                table.Columns[0].Name = "Instance";

                for (int i = 0; i < tableColumns.Count; i++)
                {
                    //table.Columns[i + 1].Name = "Column id " + tableColumns[i];
                    table.Columns[i + 1].Name = colNames[i];
                }

                foreach (KeyValuePair <string, Dictionary <uint, AsnType> > kvp in result)
                {
                    tableRows.Add(kvp.Key);
                    foreach (uint column in tableColumns)
                    {
                        if (kvp.Value.ContainsKey(column))
                        {
                            tableRows.Add(kvp.Value[column].ToString());
                        }
                        else
                        {
                            tableRows.Add("");
                        }
                    }
                    table.Rows.Add(tableRows.ToArray());
                    tableRows.Clear();
                }
            }
        }
Example #8
0
        public static void Check(CredentialsSnmp credentials)
        {
            // Populate the List of OID's to Get
            var asnItems = new Dictionary <string, SnmpAsnItem>
            {
                { BaseOid + "1.1.2.4.0", new SnmpAsnItem("Software Version") },
                { BaseOid + "1.1.2.1.0", new SnmpAsnItem("Firmware Version") },
                { BaseOid + "1.1.1.1.0", new SnmpAsnItem("Model") },
                { BaseOid + "1.2.1.3.0", new SnmpAsnItem("Battery Replacement Date") },
                { BaseOid + "1.7.2.4.0", new SnmpAsnItem("Battery Test Date") },
                { BaseOid + "1.7.2.3.0", new SnmpAsnItem("Battery Test Result") },
                { BaseOid + "1.7.2.8.0", new SnmpAsnItem("Battery Calibration Date") },
                { BaseOid + "1.7.2.7.0", new SnmpAsnItem("Battery Calibration Result") },
                { BaseOid + "4.3.1.0", new SnmpAsnItem("Humidity") },
                { BaseOid + "4.2.1.0", new SnmpAsnItem("Temperature") },
                { BaseOid + "1.1.2.3.0", new SnmpAsnItem("Serial Number") }
            };

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

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

            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 SnmpV1Packet();

            try
            {
                result = (SnmpV1Packet)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 = "CyberPower " + model;
                if (!string.IsNullOrEmpty(asnItemsLookup["Serial Number"].Value.ToString()))
                {
                    message += " SN " + asnItemsLookup["Serial Number"].Value;
                }
                message += " (SW v" + asnItemsLookup["Software Version"].Value;
                message += " / FW v" + asnItemsLookup["Firmware Version"].Value + ")";

                Channel channel;

                // Humidity
                var tempStr = asnItemsLookup["Humidity"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null")
                    {
                        channel = new Channel
                        {
                            Description = "Humidity",
                            Unit        = Unit.Percent,
                            Value       = asnItemsLookup["Humidity"].Value.ToString()
                        };
                        output.Channels.Add(channel);
                    }
                }

                // Temperature
                tempStr = asnItemsLookup["Temperature"].Value.ToString();
                if (!string.IsNullOrEmpty(tempStr))
                {
                    if (tempStr != "Null")
                    {
                        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);
                    }
                }

                // Battery Test Result
                var batteryTestResult  = asnItemsLookup["Battery Test Result"].Value.ToString().Trim();
                var batteryTestWarning = "0";
                if (batteryTestResult != "1")
                {
                    batteryTestResult  = "FAILURE";
                    batteryTestWarning = "1";
                }
                channel = new Channel
                {
                    Description = "Battery Test Result",
                    Unit        = Unit.Custom,
                    CustomUnit  = "Result",
                    Value       = batteryTestResult,
                    Warning     = batteryTestWarning
                };
                output.Channels.Add(channel);

                // Battery Calibration Result
                var batteryCalibrationResult  = asnItemsLookup["Battery Calibration Result"].Value.ToString().Trim();
                var batteryCalibrationWarning = "0";
                if (batteryCalibrationResult != "1")
                {
                    batteryCalibrationResult  = "FAILURE";
                    batteryCalibrationWarning = "1";
                }
                channel = new Channel
                {
                    Description = "Battery Calibration Result",
                    Unit        = Unit.Custom,
                    CustomUnit  = "Result",
                    Value       = batteryCalibrationResult,
                    Warning     = batteryCalibrationWarning
                };
                output.Channels.Add(channel);

                // Battery Test Date
                DateTime batteryTestDate;
                var      batteryTestDateStr = CheckDateTimeFormat(asnItemsLookup["Battery Test Date"].Value.ToString(), model);
                if (string.IsNullOrEmpty(batteryTestDateStr) || batteryTestDateStr.ToLower() == "null")
                {
                    batteryTestDate = new DateTime(2010, 01, 01);
                }
#if OLDCODE
                else
                {
                    if (model == "OL1500ERTXL2U")
                    {
                        batteryTestDate = DateTime.ParseExact(batteryTestDateStr, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        batteryTestDate = DateTime.Parse(batteryTestDateStr);
                    }
                }
#else
                else
                {
                    batteryTestDate = DateTime.Parse(batteryTestDateStr);
                }
#endif
                var daysSinceBatteryTest = Convert.ToInt16((DateTime.Now - batteryTestDate).TotalDays);
                channel = new Channel
                {
                    Description         = "Days Since Battery Test",
                    Unit                = Unit.Custom,
                    CustomUnit          = "Days",
                    LimitErrorMessage   = "Battery Test Overdue",
                    LimitWarningMessage = "Battery Test Required",
                    LimitMaxWarning     = BatteryTestWarningDays.ToString(),
                    LimitMaxError       = BatteryTestErrorDays.ToString(),
                    LimitMode           = "1",
                    Value               = daysSinceBatteryTest.ToString()
                };
                output.Channels.Add(channel);

                // Battery Calibration Date
                DateTime batteryCalibrationDate;
                var      batteryCalibrationCalibration = CheckDateTimeFormat(asnItemsLookup["Battery Calibration Date"].Value.ToString(), model);
                if (string.IsNullOrEmpty(batteryCalibrationCalibration) || batteryCalibrationCalibration.ToLower() == "null")
                {
                    batteryCalibrationDate = new DateTime(2010, 01, 01);
                }
                else
                {
                    batteryCalibrationDate = DateTime.Parse(batteryCalibrationCalibration);
                }
                var daysSinceBatteryCalibration = Convert.ToInt16((DateTime.Now - batteryCalibrationDate).TotalDays);
                channel = new Channel
                {
                    Description         = "Days Since Battery Calibration",
                    Unit                = Unit.Custom,
                    CustomUnit          = "Days",
                    LimitErrorMessage   = "Battery Calibration Overdue",
                    LimitWarningMessage = "Battery Calibration Required",
                    LimitMaxWarning     = BatteryCalibrationWarningDays.ToString(),
                    LimitMaxError       = BatteryCalibrationErrorDays.ToString(),
                    LimitMode           = "1",
                    Value               = daysSinceBatteryCalibration.ToString()
                };
                output.Channels.Add(channel);

                output.Text = message;
                output.WriteOutput();
            }
Example #9
0
        private Dictionary <string, string> GetSnmpInfo(string ipAddress, IEnumerable <string> oids)
        {
            //results will be <OID,SNMP Call Result>
            Dictionary <string, string> results = new Dictionary <string, string>();
            /********** Heavily Modified code from the SnmpSharpNet webpage **********/
            /**********      http://www.snmpsharpnet.com/?page_id=111       **********/

            // SNMP community name
            OctetString community = new OctetString("public");

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

            // Set SNMP version to 1
            param.Version = SnmpVersion.Ver1;

            // Construct the agent address object
            IpAddress agent = new IpAddress(ipAddress);

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

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

            //Add list of all relevant OIDs
            foreach (string key in oids)
            {
                pdu.VbList.Add(key);
            }

            // Make SNMP request
            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)
                {
                    //Close the connection since we're going to throw an exception.
                    target.Close();

                    // agent reported an error with the request
                    string msg = $"OID {oids.ElementAt(result.Pdu.ErrorIndex)} "
                                 + "has exited with error status "
                                 + $"{ result.Pdu.ErrorStatus}: {Enum.GetName(typeof(PduErrorStatus), result.Pdu.ErrorStatus)}";
                    throw new ImproperOidsException(msg);
                }
                else
                {
                    //Print all information we gleaned from inspecting the UPS
                    IEnumerator <Vb> EnumeratedResults = result.Pdu.GetEnumerator();
                    do
                    {
                        if (EnumeratedResults.Current == null)
                        {
                            continue;
                        }

                        //Console.WriteLine($"{UPS.Oids[EnumeratedResults.Current.Oid.ToString()],30}: {EnumeratedResults.Current.Value.ToString(),-30}");
                        results.Add(EnumeratedResults.Current.Oid.ToString(), EnumeratedResults.Current.Value.ToString());
                    } while (EnumeratedResults.MoveNext());
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();

            return(results);

            /******** END Credited Code ********/
        }
Example #10
0
        private KeyValuePair <string, string> GetSnmpResultForOid(string ipAddress, string oid)
        {
            //results will be <OID,SNMP Call Result>
            Dictionary <string, string> results = new Dictionary <string, string>();
            /********** Heavily Modified code from the SnmpSharpNet webpage **********/
            /**********      http://www.snmpsharpnet.com/?page_id=111       **********/

            // SNMP community name
            OctetString community = new OctetString("public");

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

            // Set SNMP version to 1
            param.Version = SnmpVersion.Ver1;

            // Construct the agent address object
            IpAddress agent = new IpAddress(ipAddress);

            // 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(oid);

            // Make SNMP request
            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)
                {
                    //Close the connection since we're going to throw an exception.
                    target.Close();

                    // agent reported an error with the request
                    string msg = $"OID {oid} "
                                 + "has exited with error status "
                                 + $"{ result.Pdu.ErrorStatus}: {Enum.GetName(typeof(PduErrorStatus), result.Pdu.ErrorStatus)}";
                    throw new ImproperOidsException(msg);
                }
                else
                {
                    results.Add(oid, result.Pdu.VbList[0].Value.ToString());
                }
            }
            else
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();

            return(results.Count > 0 ? new KeyValuePair <string, string>(oid, results[oid].ToString()) : new KeyValuePair <string, string>("", ""));


            /******** END Credited Code ********/
        }
Example #11
0
 public void Initialize(Manager agents, AgentParameters stats)
 {
     Group      = agents;
     Parameters = stats;
 }
Example #12
0
        // Network Discovery Info
        //// hardware master information
        //List<Hw_MasterInfoDTO> LstHw_MasterInfoDTO = new List<Hw_MasterInfoDTO>();

        //Hw_MasterInfoResponse oHw_MasterInfoResponse = new Hw_MasterInfoResponse();
        //Hw_MasterInfoDataAccess oHw_MasterInfoDataAccess = new Hw_MasterInfoDataAccess();


        #region SNMP Operations
        /// <summary>
        /// this method will pick basic information of switch
        /// throug SNMP and OIDs on the basis of IP Address and community
        ///
        /// </summary>

        public string SNMPGetRequest(string OctCommunity, string IpAddress)
        {
            List <Hw_MasterInfoDTO> LstHw_MasterInfoDTO = new List <Hw_MasterInfoDTO>();
            var oHw_MasterInfoResponse = new Hw_MasterInfoResponse();
            Hw_MasterInfoDataAccess oHw_MasterInfoDataAccess = new Hw_MasterInfoDataAccess();
            string lstResults = "";

            try
            {
                // SNMP community name
                OctetString community = new OctetString(OctCommunity);

                // 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(IpAddress);
                //IpAddress agent = new IpAddress("65.154.4.21");

                // 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.2.1.1.1.0"); //sysDescr
                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

                //

                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.12");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.13");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.14");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.15");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.16");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.17");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.18");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.19");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.20");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.21");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.22");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.23");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.24");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.25");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.26");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.27");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.28");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.29");

                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.1");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.2");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.3");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.4");
                pdu.VbList.Add("1.3.6.1.2.1.2.2.1.2.5");

                //

                // Make SNMP request
                SnmpV1Packet     result = (SnmpV1Packet)target.Request(pdu, param);
                Hw_MasterInfoDTO objHw_Info;
                // 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
                    {
                        objHw_Info             = new Hw_MasterInfoDTO();
                        objHw_Info.IPAddress   = IpAddress;
                        objHw_Info.HwTypeId    = 7; // Switch TODO: it will be fetched from DataBase's table hardware type.
                        objHw_Info.Description = result.Pdu.VbList[0].Value.ToString();
                        objHw_Info.HwName      = result.Pdu.VbList[4].Value.ToString();
                        objHw_Info.DevType     = "Machines";
                        objHw_Info.DevCategory = "IOS";
                        objHw_Info.ComType     = "Cisco IOS Software";
                        objHw_Info.StatusId    = 2;  // // Start 1, Running 2, Completed 3, Stop 4, Exception 5... Status 3 is used for Complete Running Probe
                        objHw_Info.MacAddress  = ""; //TODO: will be fetched from Switch
                        LstHw_MasterInfoDTO.Add(objHw_Info);

                        if (LstHw_MasterInfoDTO.Count > 0)
                        {
                            // ProbeDBEntities _Db = new ProbeDBEntities();
                            oHw_MasterInfoResponse = oHw_MasterInfoDataAccess.Hw_MasterInfo_InsertData(LstHw_MasterInfoDTO); // By Umar
                        }

                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        lstResults = "System Description :" + result.Pdu.VbList[0].Value.ToString() + "\n";
                        Console.WriteLine("sysDescr({0}) ({1}): {2}",
                                          result.Pdu.VbList[0].Oid.ToString(),
                                          SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                                          result.Pdu.VbList[0].Value.ToString());

                        lstResults = lstResults + "System Object ID: " + result.Pdu.VbList[1].Value.ToString() + "\n";
                        Console.WriteLine("sysObjectID({0}) ({1}): {2}",
                                          result.Pdu.VbList[1].Oid.ToString(),
                                          SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type),
                                          result.Pdu.VbList[1].Value.ToString());
                        lstResults = lstResults + "System Up Time: " + result.Pdu.VbList[2].Value.ToString() + "\n";
                        Console.WriteLine("sysUpTime({0}) ({1}): {2}",
                                          result.Pdu.VbList[2].Oid.ToString(),
                                          SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type),
                                          result.Pdu.VbList[2].Value.ToString());
                        lstResults = lstResults + "System Conatct: " + result.Pdu.VbList[3].Value.ToString() + "\n";
                        Console.WriteLine("sysContact({0}) ({1}): {2}",
                                          result.Pdu.VbList[3].Oid.ToString(),
                                          SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type),
                                          result.Pdu.VbList[3].Value.ToString());
                        lstResults = lstResults + "System Name: " + result.Pdu.VbList[4].Value.ToString() + "\n";
                        Console.WriteLine("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
                {
                    Console.WriteLine("No response received from SNMP agent.");
                    lstResults = "No response received from SNMP agent.";
                }
                target.Close();
            }
            catch (Exception ex)
            {
                lstResults = "Code Breaks :" + ex.Message;
                return(lstResults);
            }

            //WriteTextFile.WriteErrorLog("============================ SWITCH Information ====================================");
            //  WriteTextFile.WriteErrorLog(lstResults);

            //  WriteTextFile.WriteErrorLog("============================ SWITCH Information ====================================");

            return(lstResults);
        }
Example #13
0
        private void ConstructListByIP(IpAddress agentIP, string equipName)
        {
            if (string.IsNullOrEmpty(equipName))
            {
                try
                {
                    equipName = App.idAndEquipList[App.ipAndIPinfoList[agentIP.ToString()].EquipIndex].Name;
                }
                catch { }
            }
            ocInterfaces.Clear();
            OctetString     community = new OctetString(App.snmpCommunity);
            AgentParameters param     = new AgentParameters(community);

            param.DisableReplySourceCheck = !App.snmpCheckSrcFlag;
            // 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, App.snmpPort, App.snmpTimeout, App.snmpRetry);

            // 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.1"); // ifIndex

            // 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 = null;
                try
                {
                    result = (SnmpV2Packet)target.Request(pdu, param);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("获取SNMP应答出现错误\n" + ex.Message);
                    target.Close();
                    return;
                }
                // 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
                        MessageBox.Show(string.Format("SNMP应答数据包中有错误。 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))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid = null;
                                }
                                else
                                {
                                    lastOid = v.Oid;
                                }
                                Integer32 f    = v.Value as Integer32;
                                Interface intf = new Interface(agentIP);
                                intf.EquipName = equipName;
                                //intf.TimerInteral = double.Parse(cbbTimerInterval.Text);
                                ocInterfaces.Add(f, intf);
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                                break; // 每个数据包获取5个值,一旦有一个不是这一列的数据,后面的应该都不是了
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("指定网管代理未返回有效信息");
                }
            }
            target.Close();
            string errorMessage;

            foreach (Integer32 i in ocInterfaces.Keys)
            {
                string       strOid = "1.3.6.1.2.1.2.2.1.2." + i.ToString();
                VbCollection vbc    = SnmpHelper.GetResultsFromOids(agentIP, new string[] { strOid }, out errorMessage);
                ocInterfaces[i].Descr   = vbc[0].Value.ToString();
                ocInterfaces[i].IfIndex = i;
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            // SNMP community name
            OctetString community = new OctetString("abcBolinhas");

            // 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("127.0.0.1");

            // 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.2.1.1.1.0"); //sysDescr
            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

            // Make SNMP request
            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
                    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
                    Console.WriteLine("sysDescr({0}) ({1}): {2}",
                                      result.Pdu.VbList[0].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                                      result.Pdu.VbList[0].Value.ToString());
                    Console.WriteLine("sysObjectID({0}) ({1}): {2}",
                                      result.Pdu.VbList[1].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[1].Value.Type),
                                      result.Pdu.VbList[1].Value.ToString());
                    Console.WriteLine("sysUpTime({0}) ({1}): {2}",
                                      result.Pdu.VbList[2].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[2].Value.Type),
                                      result.Pdu.VbList[2].Value.ToString());
                    Console.WriteLine("sysContact({0}) ({1}): {2}",
                                      result.Pdu.VbList[3].Oid.ToString(),
                                      SnmpConstants.GetTypeName(result.Pdu.VbList[3].Value.Type),
                                      result.Pdu.VbList[3].Value.ToString());
                    Console.WriteLine("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
            {
                Console.WriteLine("No response received from SNMP agent.");
            }
            target.Close();
        }
Example #15
0
        public List <WalkTowerDevice> WalkSendReturn(string IP, int Port, string Version, string communityRead, List <WalkTowerDevice> walkList, string towerName, string DeviceName, int deviceID)
        {
            string walkTimeOutOID = "";

            using (IDbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DeviceConnection"].ConnectionString))
            {
                var mibInf = connection.Query <MibTreeInformation>("Select * From  [TreeInformation]").ToList();

                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);
                Oid       rootOid = new Oid(".1.3.6.1");

                Oid lastOid = (Oid)rootOid.Clone();

                Pdu pdu = new Pdu(PduType.GetNext);

                while (lastOid != null)
                {
                    try
                    {
                        if (pdu.RequestId != 0)
                        {
                            pdu.RequestId += 1;
                        }
                        pdu.VbList.Clear();
                        pdu.VbList.Add(lastOid);
                        if (walkTimeOutOID == lastOid.ToString())
                        {
                            WalkTimeOunt++;
                        }
                        if (WalkTimeOunt <= 10)
                        {
                            walkTimeOutOID = lastOid.ToString();
                        }
                        else
                        {
                            return(walkList);
                        }

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

                        if (result != null)
                        {
                            if (result.Pdu.ErrorStatus != 0)
                            {
                                lastOid = null;
                                break;
                            }
                            else
                            {
                                foreach (Vb v in result.Pdu.VbList)
                                {
                                    if (rootOid.IsRootOf(v.Oid))
                                    {
                                        WalkTowerDevice walk = new WalkTowerDevice();
                                        ID++;
                                        walk.ID     = ID;
                                        walk.WalkID = ID;
                                        string oid = v.Oid.ToString();
                                        var    OidMibdescription = mibInf.Where(m => m.OID == oid).FirstOrDefault();
                                        if (OidMibdescription == null)
                                        {
                                            oid = oid.Remove(oid.Length - 1);
                                            oid = oid.Remove(oid.Length - 1);
                                            OidMibdescription = mibInf.Where(o => o.OID == oid).FirstOrDefault();
                                        }
                                        if (OidMibdescription == null)
                                        {
                                            oid = oid.Remove(oid.Length - 1);
                                            oid = oid.Remove(oid.Length - 1);
                                            OidMibdescription = mibInf.Where(o => o.OID == oid).FirstOrDefault();

                                            if (OidMibdescription != null)
                                            {
                                                walk.WalkDescription = OidMibdescription.Description;
                                            }
                                        }
                                        else
                                        {
                                            walk.WalkDescription = OidMibdescription.Description;
                                        }
                                        if (OidMibdescription != null)
                                        {
                                            walk.WalkDescription = OidMibdescription.Description;
                                        }
                                        else
                                        {
                                            walk.WalkDescription = "Is Not Description";
                                        }
                                        walk.WalkOID = v.Oid.ToString();
                                        var oidname = mibInf.Where(o => o.OID == oid).FirstOrDefault();

                                        if (oidname != null)
                                        {
                                            walk.OIDName = oidname.Name;
                                        }
                                        else
                                        {
                                            walk.OIDName = "Is Not Name";
                                        }
                                        walk.Type         = v.Value.ToString();
                                        walk.Value        = SnmpConstants.GetTypeName(v.Value.Type);
                                        walk.ScanInterval = 60;
                                        walk.DeviceName   = DeviceName;
                                        walk.TowerName    = towerName;
                                        walk.DeviceID     = deviceID;
                                        walk.IP           = IP;
                                        walk.Version      = Version;

                                        //walk.StartCorrect = "0";
                                        //walk.EndCorrect = "0";
                                        //walk.OneStartError = "0";
                                        //walk.OneEndError = "0";
                                        //walk.OneStartCrash = "0";
                                        //walk.OneEndCrash = "0";
                                        //walk.TwoStartError = "0";
                                        //walk.TwoEndError = "0";
                                        //walk.TwoStartCrash = "0";
                                        //walk.TwoEndCrash = "0";

                                        walkList.Add(walk);
                                        lastOid = v.Oid;
                                    }
                                    else
                                    {
                                        lastOid = null;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e) { }
                }
                target.Close();
            }
            return(walkList);
        }
 private int getSNMPParam(string ipAddr, SnmpSharpNet.Oid oid_needed)
 {
     try
     {
         OctetString     community = new OctetString("public");
         AgentParameters param     = new AgentParameters(community);
         param.Version = SnmpVersion.Ver2;
         IpAddress agent   = new IpAddress(ipAddr);
         UdpTarget target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
         Oid       rootOid = new Oid(oid_needed);
         Oid       lastOid = (Oid)rootOid.Clone();
         Pdu       pdu     = new Pdu(PduType.GetBulk);
         pdu.NonRepeaters   = 0;
         pdu.MaxRepetitions = 5;
         while (lastOid != null)
         {
             if (pdu.RequestId != 0)
             {
                 pdu.RequestId += 1;
             }
             pdu.VbList.Clear();
             pdu.VbList.Add(lastOid);
             try
             {
                 SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                 if (result != null)
                 {
                     if (result.Pdu.ErrorStatus != 0)
                     {
                         throw new NullReferenceException();
                     }
                     else
                     {
                         foreach (Vb v in result.Pdu.VbList)
                         {
                             if (rootOid.IsRootOf(v.Oid))
                             {
                                 if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                 {
                                     lastOid = null;
                                 }
                                 else
                                 {
                                     lastOid = v.Oid;
                                 }
                                 target.Close();
                                 return(Convert.ToInt32(v.Value));
                             }
                             else
                             {
                                 lastOid = null;
                             }
                         }
                     }
                 }
                 else
                 {
                     throw new NullReferenceException();
                 }
             }
             catch (NullReferenceException)
             {
             }
         }
         target.Close();
         return(0);
     }
     catch (Exception)
     {
         return(0);
     }
 }
Example #17
0
        public bool BulkWalkTest(string strHost, string strCommunity, string[] strOids)
        {
            // SNMP community name
            OctetString community = new OctetString(strCommunity);
            // 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(strHost);
            bool      returnValue = false;
            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            try
            {
                foreach (string strOid in strOids)
                {
                    // Define Oid that is the root of the MIB
                    //  tree you wish to retrieve
                    Oid rootOid = new Oid(strOid); // 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
                                string errorMsg = string.Format("Error in SNMP reply. Error {0} index {1}",
                                                                result.Pdu.ErrorStatus,
                                                                result.Pdu.ErrorIndex);
                                throw new Exception(errorMsg);
                                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.");
                            throw new Exception("No response received from SNMP agent.");
                        }
                    }
                }
                returnValue = true;
            }
            catch (Exception ex)
            {
                returnValue = false;
            }
            finally
            {
                target.Close();
            }
            return(returnValue);
        }
Example #18
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);
        }
Example #19
0
        static int SNMPGet(string mac, string ip)
        {
            // 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.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(ip);

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

            Oid rootOid = new Oid(".1.3.6.1.2.1.17.7.1.2.2.1.2.1");  // dot1qTpFdbPort, .iso.org.dod.internet.mgmt.mib-2.dot1dBridge.qBridgeMIB.qBridgeMIBObjects.dot1qTp.dot1qTpFdbTable.dot1qTpFdbEntry.dot1qTpFdbPort
            Oid lastOid = (Oid)rootOid.Clone();

            Pdu pdu = new Pdu(PduType.GetNext);

            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to a random value
                // that needs to be incremented on subsequent requests made using the
                // same instance of the Pdu class.
                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.Oid.ToString().EndsWith(mac))
                                {
                                    target.Close();
                                    return(Convert.ToInt32(v.Value.ToString()));
                                }
                                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(-1);
        }
Example #20
0
        static Dictionary <string, string> WalkJob(string host, string oid)
        {
            Dictionary <string, string> values = new Dictionary <string, string>();

            // SNMP community name
            try
            {
                OctetString community = new OctetString("public");

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 1
                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(host);

                // 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(oid); // 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.GetNext);

                // Loop through results
                while (lastOid != null)
                {
                    // When Pdu class is first constructed, RequestId is set to a random value
                    // that needs to be incremented on subsequent requests made using the
                    // same instance of the Pdu class.
                    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
                    SnmpV1Packet result = (SnmpV1Packet)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))
                                {
                                    //Debug.WriteLine("{0} ({1}): {2}",
                                    //    v.Oid.ToString(),
                                    //    SnmpConstants.GetTypeName(v.Value.Type),
                                    //    v.Value.ToString());
                                    values.Add(v.Oid.ToString(), v.Value.ToString());
                                    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();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }
            return(values);
        }
Example #21
0
        private void GetResponse()
        {
            connection = new Connection(IpAddress, Port, SnmpVersion, Community, Retries, Timeout);

            // SNMP community name
            OctetString community = new OctetString("abcBolinhas");

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

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

            // 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
            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

            // 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
                    MessageBox.Show("Error in SNMP reply. Error {0} index {1}", Convert.ToString(result.Pdu.ErrorStatus), MessageBoxButtons.OK);
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList

                    equipment = new Equipment();

                    equipment.Description = "oid(" + result.Pdu.VbList[0].Oid.ToString() + ")" +
                                            " " + result.Pdu.VbList[0].Value.ToString();
                    equipment.Contact = "oid(" + result.Pdu.VbList[3].Oid.ToString() + ")" +
                                        " " + result.Pdu.VbList[3].Value.ToString();
                    equipment.Name = "oid(" + result.Pdu.VbList[4].Oid.ToString() + ")" +
                                     " " + result.Pdu.VbList[4].Value.ToString();
                    equipment.Location = "oid(" + result.Pdu.VbList[1].Oid.ToString() + ")" +
                                         " " + result.Pdu.VbList[1].Value.ToString();
                    equipment.UpTime = "oid(" + result.Pdu.VbList[2].Oid.ToString() + ")" +
                                       " " + result.Pdu.VbList[2].Value.ToString();

                    UpdateFields();
                }
            }
            else
            {
                MessageBox.Show("No response received from SNMP agent.", "Fail", MessageBoxButtons.OK);
            }
        }
Example #22
0
        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();
        }
Example #23
0
    private static Bandwidth GetBandwidth(string Site, string IP)
    {
        try
        {
            var community = new OctetString("public");

            var param = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver1
            };

            var agent = new IpAddress(IP);

            using (var target = new UdpTarget((IPAddress)agent, 161, 2000, 1))
            {
                var pdu = new Pdu(PduType.Get);
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.5.1");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.10.1");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.16.1");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.5.2");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.10.2");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.16.2");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.5.3");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.10.3");
                pdu.VbList.Add(".1.3.6.1.2.1.2.2.1.16.3");

                var result = (SnmpV1Packet)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
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        var bw = new Bandwidth
                        {
                            Id = Guid.NewGuid(),
                            DeviceIPAddress = IP,
                            Site            = Site,
                            Timestamp       = DateTime.Now,
                            X0Speed         = Convert.ToDouble(result.Pdu.VbList[0].Value.ToString()),
                            X0Ingress       = Convert.ToDouble(result.Pdu.VbList[1].Value.ToString()),
                            X0Egress        = Convert.ToDouble(result.Pdu.VbList[2].Value.ToString()),
                            X1Speed         = Convert.ToDouble(result.Pdu.VbList[3].Value.ToString()),
                            X1Ingress       = Convert.ToDouble(result.Pdu.VbList[4].Value.ToString()),
                            X1Egress        = Convert.ToDouble(result.Pdu.VbList[5].Value.ToString()),
                            X2Speed         = Convert.ToDouble(result.Pdu.VbList[6].Value.ToString()),
                            X2Ingress       = Convert.ToDouble(result.Pdu.VbList[7].Value.ToString()),
                            X2Egress        = Convert.ToDouble(result.Pdu.VbList[8].Value.ToString())
                        };

                        return(bw);
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
                target.Close();
                return(null);
            }
        }
        catch (Exception e) { Console.WriteLine(e); return(null); }
    }