示例#1
0
        /// <summary>
        /// Converts the given byte array to an OID.<br/>
        /// Optionally, the constructed OID will be appended at the end of the <paramref name="rootOid" />.paramref name="rootOid"<br/>
        /// For example: byte[] { 0xb8, 0x27, 0xeb, 0x97, 0xb6, 0x39 } will convert to "184.39.235.151.182.57".
        /// </summary>
        /// <param name="bytes">The byte array to convert.</param>
        /// <param name="rootOid">The root OID to append the converted byte array to.</param>
        /// <returns>A byte array with the hex values of the string.</returns>
        public static Oid ToDottedDecimalOid(this byte[] bytes, Oid rootOid = null)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes), "The bytes array to convert is null");
            }

            Oid returnOid = (Oid)rootOid?.Clone() ?? new Oid();

            returnOid.Add(bytes.ToDottedDecimalString());

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

            if (string.IsNullOrEmpty(tableVb.ColumnOid))
            {
                oid2 = (Oid)oid.Clone();
            }
            else
            {
                oid2 = new Oid(tableVb.ColumnOid);
            }
            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            while (oid2 != null)
            {
                pdu.VbList.Clear();
                pdu.VbList.Add(oid2);
                SnmpPacket snmpPacket = target.Request(pdu, param);
                this.validateResponse(snmpPacket, pdu);
                foreach (Vb current in snmpPacket.Pdu.VbList)
                {
                    if (!oid.IsRootOf(current.Oid))
                    {
                        oid2 = null;
                        break;
                    }
                    if (current.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                    {
                        oid2 = null;
                        break;
                    }
                    string key = current.Oid.ToString();
                    if (!dictionary.ContainsKey(key))
                    {
                        dictionary.Add(key, current.Value.ToString());
                        oid2 = current.Oid;
                    }
                }
            }
            return(dictionary);
        }
示例#3
0
        public static Dictionary <string, string> getWalkValue_v3(string host, int port, int snmpver, string comm, string irootOid)
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();
            // SNMP community name
            OctetString community = new OctetString(comm);

            // 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.Ver3;
            // 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, port, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(irootOid); // 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 = 1000;
            try
            {
                // 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
                    SnmpV3Packet result = new SnmpV3Packet();
                    result.authPriv(ASCIIEncoding.UTF8.GetBytes("milan"),
                                    ASCIIEncoding.UTF8.GetBytes("myAuthSecret"), AuthenticationDigests.MD5,
                                    ASCIIEncoding.UTF8.GetBytes("myPrivSecret"), PrivacyProtocols.DES);
                    result = (SnmpV3Packet)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)
                        {
                            // 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))
                                {
                                    dic.Add(v.Oid.ToString(), v.Value.ToString());
                                }
                                else
                                {
                                    // we have reached the end of the requested
                                    // MIB tree. Set lastOid to null and exit loop
                                    lastOid = null;
                                }
                            }
                        }
                    }
                }
                target.Close();
                return(dic);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                target.Close();
                return(dic);
            }
        }
示例#4
0
        private List <Vb> ReadFdbPortTable(SnmpTarget snmpTarget)
        {
            var community = new OctetString(
                string.IsNullOrEmpty(snmpTarget.Community) ? "public" : snmpTarget.Community);
            var param = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver2
            };
            var agent   = new IpAddress(snmpTarget.IpAddress);
            var target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            var rootOid = new Oid(SnmpOids.Dot1DTpFdbPort);
            var lastOid = (Oid)rootOid.Clone();
            var pdu     = new Pdu(PduType.GetBulk)
            {
                NonRepeaters = 0, MaxRepetitions = 5
            };
            var results = new List <Vb>();

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                var result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        break;
                    }

                    foreach (var v in result.Pdu.VbList)
                    {
                        if (rootOid.IsRootOf(v.Oid))
                        {
                            Console.WriteLine("{0} ({1}): {2}",
                                              v.Oid,
                                              SnmpConstants.GetTypeName(v.Value.Type),
                                              v.Value);

                            results.Add(v);

                            lastOid = v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ? null : v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(results);
        }
示例#5
0
        public void Update()
        {
            Oid rootOid = new Oid("1.3.6.1.2.1.31.1.1.1.1.2");
            Oid lastOid = (Oid)rootOid.Clone();

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId++;
                }

                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);

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

                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        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();

            /*SnmpV2Packet result =  null;
             *
             * try
             * {
             *  result = (SnmpV2Packet)target.Request(pdu, param);
             * } catch(Exception e)
             * {
             *  Console.WriteLine(e.Message);
             * }
             *
             * if (result != null)
             * {
             *  if (result.Pdu.ErrorStatus != 0)
             *  {
             *      Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
             *          result.Pdu.ErrorStatus,
             *          result.Pdu.ErrorIndex);
             *  }
             *  else
             *  {
             *      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.");
             * }*/
        }
示例#6
0
        public void GetTree()
        {
            int counter = 0;

            param.Version = SnmpVersion.Ver1;
            Oid rootOid = new Oid("1.3.6.1.2.1");
            Oid lastOid = (Oid)rootOid.Clone();
            Pdu pdu     = new Pdu(PduType.GetNext);

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus, result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                OidNumber = v.Oid.ToString();
                                string temp = OidNumber.Substring(OidNumber.Length - 2);
                                if (temp == ".0")
                                {
                                    counter = 0;
                                    string name = translate(OidNumber.Remove(OidNumber.Length - 2), null);
                                    if (name != null)
                                    {
                                        lista.Add(new Dane(v.Oid.ToString(), name));
                                    }
                                }
                                else
                                {
                                    if (translate(lastOid.ToString().Remove(lastOid.ToString().Length - 2), null) != null && counter == 0)
                                    {
                                        int    length = lastOid.ToString().Length - 2;
                                        string oid    = OidNumber.Substring(0, length);
                                        string name   = translate(oid, null);
                                        if (name != null)
                                        {
                                            lista.Add(new Dane(oid, name));
                                            counter++;
                                        }
                                    }
                                }
                                lastOid = v.Oid;
                            }
                            else
                            {
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            foreach (var i in lista)
            {
                if (OidNumber.Contains("1.3.6.1.2.1.55"))
                {
                    break;
                }
            }
        }
示例#7
0
    /// <summary>
    /// Will get the rest of the variables, parts and percentages
    /// </summary>
    private Dictionary<String, String> getData()
    {
        Dictionary<String, String> dictionary = new Dictionary<String, String>();
        OctetString community = new OctetString( "public" );
        AgentParameters param = new AgentParameters( community );
        param.Version = SnmpVersion.Ver1;
        IpAddress agent = new IpAddress( printerName );

        UdpTarget target = new UdpTarget( (System.Net.IPAddress)agent, 161, 2000, 1 );
        Oid rootOid = new Oid( printerOID ); // ifDescr
        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
            SnmpV1Packet result = null;
            try
            {
                result = (SnmpV1Packet)target.Request( pdu, param );
            }
            catch
            {
                return null;
            }

            // 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 ) )
                        {
                            dictionary.Add( v.Oid.ToString(), v.Value.ToString() );
                            lastOid = v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine( "No response received from SNMP agent." );
            }
        }
        target.Close();

        return dictionary;
    }
        private void snmpwalk()
        {
            try
            {
                string hexstr = @"[0-9a-fA-F]{2}\s[0-9a-fA-F]{2}\s[0-9a-fA-F]{2}\s";
                //匹配连续三组十六进制字符的正则式
                Regex           regex     = new Regex(hexstr);
                OctetString     community = new OctetString("public");
                AgentParameters param     = new AgentParameters(community);
                param.Version = SnmpVersion.Ver1;
                IpAddress agent  = new IpAddress(Common.getipbyid(id));
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                List <string> miblist = Common.getmonitoritems(id);
                //Dictionary<string, string> output_cache = new Dictionary<string, string>();
                Pdu pdu = new Pdu(PduType.GetNext);
                for (int i = 0; i < miblist.Count; i++)
                {
                    Oid rootOid = new Oid(miblist[i]);
                    Oid lastOid = (Oid)rootOid.Clone();
                    while (lastOid != null)
                    {
                        string resultstring = null;
                        if (pdu.RequestId != 0)
                        {
                            pdu.RequestId += 1;
                        }
                        pdu.VbList.Clear();
                        pdu.VbList.Add(lastOid);
                        SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                        if (result != null)
                        {
                            if (result.Pdu.ErrorStatus != 0)
                            {
                                Common.writetologfrm(string.Format("SNMP Walk(GET-Next错误),错误号:{0} 错误位置:{1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex));
                                lastOid = null;
                                break;
                            }
                            else
                            {
                                foreach (Vb vb in result.Pdu.VbList)
                                {       //检查子节点
                                    if (rootOid.IsRootOf(vb.Oid))
                                    {
                                        //如果字符是三组16进制开头的,则转码成中文
                                        string          sourcevalue = vb.Value.ToString();
                                        MatchCollection matchlist   = regex.Matches(sourcevalue);
                                        if (matchlist.Count > 0)
                                        {
                                            sourcevalue   = sourcevalue.Replace(" ", "");
                                            resultstring += getchsfromhex(sourcevalue);
                                        }
                                        else
                                        {
                                            resultstring += vb.Value.ToString();
                                        }
                                        resultstring += "\r\n---------------------------------\r\n";
                                        lastOid       = vb.Oid;
                                        //键与值加入dictionary
                                        dict.Add(vb.Oid.ToString(), resultstring);
                                    }
                                    else
                                    {    //到尾后清空oid
                                        lastOid = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            Common.writetologfrm("SNMP Walk(GET-Next)未能收到回复");
                        }
                    }
                    //获取中文名,与oid合并后加入listbox
                    string    tmpstr  = "sys_mib='" + rootOid + "'";
                    DataRow[] dr      = Common.dt_snmp_allitems.Select(tmpstr);
                    string    chsname = dr[0]["sys_service"].ToString();
                    list_items.Items.Add(chsname + "@" + rootOid.ToString());
                }
            }
            catch (Exception e) {
                MessageBox.Show(string.Format("获取SNMP消息遇到错误!\r\n{0}", e.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#9
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();
                }
            }
        }
示例#10
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);
        }
示例#11
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);
        }
示例#12
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);
        }
示例#13
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();
                }
            }
        }
示例#14
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;
            }
        }
示例#15
0
        /// <summary>
        /// Performs SNMP walk using Ver 1 GetNext operation.
        /// </summary>
        /// <param name="interfaceIdWalkRootOid">The retrievable value to start walking at. The actual OID is resolved from the device database.</param>
        /// <returns>A <see cref="VbCollection" /> with the received data.</returns>
        /// <remarks>Derived from example code at <see href="http://www.snmpsharpnet.com/?page_id=108" />.</remarks>
        private VbCollection DoWalkGetNext(Oid interfaceIdWalkRootOid)
        {
            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)interfaceIdWalkRootOid.Clone();

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

            VbCollection returnCollection = new VbCollection();

            // 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.
                Interlocked.CompareExchange(ref nextRequestId, 0, int.MaxValue); // wrap the request ID
                pdu.RequestId = Interlocked.Increment(ref nextRequestId);

                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();

                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);

                SnmpV1Packet result;
                using (var target = new UdpTarget((IPAddress)this.Address, this.Options.Port, Convert.ToInt32(this.Options.Timeout.TotalMilliseconds), this.Options.Retries))
                {
                    // Make SNMP request
                    result = (SnmpV1Packet)target.Request(pdu, this.QueryParameters);
                }

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

                // You should catch exceptions in the Request if using in real application.
                // [DJ3MU] : Yeah - cool idea - but I still wouldn't know what else to do with them.
                //           So for now, let fly them out to our caller.

                // 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
                        log.Warn($"Error in SNMP reply of device '{this.Address}': Error status {result.Pdu.ErrorStatus} at index {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 (interfaceIdWalkRootOid.IsRootOf(v.Oid))
                            {
                                returnCollection.Add(v);

                                lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    throw new HamnetSnmpException($"No response received from SNMP agent for device '{this.Address}'", this.Address?.ToString());
                }
            }

            return(returnCollection);
        }
示例#16
0
        public PartialViewResult WalkEditPreset(int?page, string presetName)
        {
            walkSearch.Clear();
            SearchNameWalk = "";

            if (presetName != "Preset" && presetName != "Select" && presetName != "All")
            {
                Checked.Clear();
                Time.Clear();
                All            = "All";
                Select         = "";
                ViewBag.All    = All;
                ViewBag.Select = Select;

                var preset = db.Presets.Where(p => p.PresetName == presetName).FirstOrDefault();
                PresetEditName = presetName;
                PresetIND      = 0;
                walkList.Clear();
                ViewBag.IP = IPadrress;


                var devicename = db.devicesTypes.Where(d => d.ID == preset.DeviceTypeID).FirstOrDefault();
                var walkOid    = db.MibTreeInformations.Where(m => m.DeviceID == devicename.ID).FirstOrDefault();

                OctetString community = new OctetString("public");

                AgentParameters param = new AgentParameters(community);
                param.Version = SnmpVersion.Ver2;

                IpAddress agent = new IpAddress(preset.DeviceIP);

                UdpTarget target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Oid       rootOid = new Oid(walkOid.OID); // ifDescr

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

                Pdu pdu = new Pdu(PduType.GetNext);

                while (lastOid != null)
                {
                    if (pdu.RequestId != 0)
                    {
                        pdu.RequestId += 1;
                    }
                    pdu.VbList.Clear();
                    pdu.VbList.Add(lastOid);
                    SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                    if (result != null)
                    {
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                WalkDevice walk = new WalkDevice();
                                ID++;
                                string oid = "." + v.Oid.ToString();
                                var    OidMibdescription = db.MibTreeInformations.Where(m => m.OID == oid).FirstOrDefault();
                                if (OidMibdescription == null)
                                {
                                    oid = oid.Remove(oid.Length - 1);
                                    oid = oid.Remove(oid.Length - 1);
                                    OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                }
                                if (OidMibdescription == null)
                                {
                                    oid = oid.Remove(oid.Length - 1);
                                    oid = oid.Remove(oid.Length - 1);
                                    OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                    if (OidMibdescription != null)
                                    {
                                        walk.WalkDescription = OidMibdescription.Description;
                                    }
                                }
                                else
                                {
                                    walk.WalkDescription = OidMibdescription.Description;
                                }
                                walk.ID     = ID;
                                walk.WalkID = ID;
                                if (OidMibdescription != null)
                                {
                                    walk.WalkOID = v.Oid.ToString();
                                }
                                //if (OidMibdescription!=null)
                                //walk.WalkDescription = OidMibdescription.Description;
                                walk.Type = v.Value.ToString();

                                walk.Time = 60;
                                walkList.Add(walk);
                                lastOid = v.Oid;
                            }
                            else
                            {
                                lastOid = null;
                            }
                        }
                    }
                }
                target.Close();

                var CheckedItem = db.WalkDevices.Where(w => w.PresetID == preset.ID).ToList();
                foreach (var ch in CheckedItem)
                {
                    Checked.Add(ch.WalkID);
                    string[] s = { ch.WalkID.ToString(), ch.Time.ToString() };
                    Time.Add(s);

                    ViewBag.Tim    = Time;
                    ViewBag.Checke = Checked;
                }
                ViewBag.Tim    = Time;
                ViewBag.Checke = Checked;
            }
            else
            {
                var preset_edit = db.Presets.Where(p => p.PresetName == PresetEditName).FirstOrDefault();

                ViewBag.Tim    = Time;
                ViewBag.Checke = Checked;

                if (presetName == "All")
                {
                    All            = "All";
                    Select         = "";
                    ViewBag.All    = All;
                    ViewBag.Select = Select;
                    PresetIND      = 0;
                    return(PartialView("_WalkView", walkList.ToPagedList(page ?? 1, viewSearch)));
                }
                if (presetName == "Select")
                {
                    Select         = "Select";
                    All            = "";
                    ViewBag.Select = Select;
                    ViewBag.All    = All;
                    PresetIND      = 1;
                    walkListEdit.Clear();
                    foreach (var ch in Checked)
                    {
                        walkListEdit.Add(walkList[ch - 1]);
                    }

                    return(PartialView("_WalkView", walkListEdit.ToPagedList(page ?? 1, viewSearch)));
                }
            }


            EditInd      = 1;
            ViewBag.Edit = EditInd;
            return(PartialView("_WalkView", walkList.ToPagedList(page ?? 1, viewSearch)));
        }
示例#17
0
        public static void TestOidCollection()
        {
            int i;
            OidCollection c = new OidCollection();
            Assert.Equal(0, c.Count);

            Oid o0 = new Oid(SHA1_Oid, SHA1_Name);
            i = c.Add(o0);
            Assert.Equal(0, i);

            Oid o1 = new Oid(SHA256_Oid, SHA256_Name);
            i = c.Add(o1);
            Assert.Equal(1, i);

            Assert.Equal(2, c.Count);

            Assert.Same(o0, c[0]);
            Assert.Same(o1, c[1]);
            Assert.Throws<ArgumentOutOfRangeException>(() => GC.KeepAlive(c[-1]));
            Assert.Throws<ArgumentOutOfRangeException>(() => GC.KeepAlive(c[c.Count]));

            Oid o2 = new Oid(SHA1_Oid, SHA1_Name);
            i = c.Add(o2);
            Assert.Equal(2, i);

            // If there multiple matches, the one with the lowest index wins.
            Assert.Same(o0, c[SHA1_Name]);
            Assert.Same(o0, c[SHA1_Oid]);

            Assert.Same(o1, c[SHA256_Name]);
            Assert.Same(o1, c[SHA256_Oid]);

            Oid o3 = new Oid(null, null);
            i = c.Add(o3);
            Assert.Equal(3, i);
            Assert.Throws<ArgumentNullException>(() => GC.KeepAlive(c[null]));

            Object o = c["BOGUSBOGUS"];
            Assert.Null(c["BOGUSBOGUS"]);

            Oid[] a = new Oid[10];
            for (int j = 0; j < a.Length; j++)
            {
                a[j] = new Oid(null, null);
            }
            Oid[] a2 = (Oid[])(a.Clone());

            c.CopyTo(a2, 3);
            Assert.Equal(a[0], a2[0]);
            Assert.Equal(a[1], a2[1]);
            Assert.Equal(a[2], a2[2]);
            Assert.Equal(o0, a2[3]);
            Assert.Equal(o1, a2[4]);
            Assert.Equal(o2, a2[5]);
            Assert.Equal(o3, a2[6]);
            Assert.Equal(a[7], a2[7]);
            Assert.Equal(a[8], a2[8]);
            Assert.Equal(a[9], a2[9]);

            Assert.Throws<ArgumentNullException>(() => c.CopyTo(null, 0));
            Assert.Throws<ArgumentNullException>(() => c.CopyTo(null, -1));
            Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, -1));
            Assert.Throws<ArgumentException>(() => c.CopyTo(a, 7));
            Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, 1000));

            ICollection ic = c;
            Assert.Throws<ArgumentException>(() => ic.CopyTo(new Oid[4, 3], 0));
            Assert.Throws<InvalidCastException>(() => ic.CopyTo(new string[100], 0));

            return;
        }
示例#18
0
        public Dictionary<string, string> walk(UdpTarget target, string oid)
        {
            Dictionary<string, string> Output = new Dictionary<string, string>();
            // 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);

            if (useCache == true ) {
                Dictionary<string, string> data = getCache(target, oid);
                if (data.Count > 0 ) {
                    return data;
                }
            }

            // 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))
                            {
                                /*
                                  Console.WriteLine("{0} ({1}): {2}",
                                    v.Oid.ToString(),
                                    SnmpConstants.GetTypeName(v.Value.Type),
                                    v.Value.ToString());
                                 */
                                // keep the result
                                Output.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.");
                }
            }

            if (useCache == true || overrideCache == true ) {
                setCache(target, oid, Output);
            }
            return Output;
        }
 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);
     }
 }
示例#20
0
        private void GetTable(Oid oid)
        {
            SnmpV2Packet localResult = new SnmpV2Packet();

            //table[n] wskazuje kolumny
            //table[n][m] wskazuje konkretne komórki
            List <List <String> > table     = new List <List <String> >();
            List <string>         columnOID = new List <string>();

            // This is the table OID supplied on the command line
            Oid startOid = oid;

            // Each table OID is followed by .1 for the entry OID. Add it to the table OID
            // Add Entry OID to the end of the table OID
            startOid.Add(1);

            // Current OID will keep track of the last retrieved OID and be used as
            //  indication that we have reached end of table
            Oid currentOid = (Oid)startOid.Clone();
            Oid prevOid    = null;

            // Keep looping through results until end of table
            // startOid.IsRootOf(curOid)
            // Compares the passed object identifier against self to determine if self is the root of the passed object.
            // If the passed object is in the same root tree as self then a true value is returned.
            // Otherwise a false value is returned from the object.
            while (true)
            {
                //make GetNext
                localResult = _mainForm.GetNextRequest(currentOid);

                //set prev before changing current
                prevOid = currentOid;
                uint[] prevChildOids = Oid.GetChildIdentifiers(startOid, prevOid);

                //set OID result to currentOid
                currentOid = localResult.Pdu.VbList[0].Oid;

                // Make sure we are dealing with an OID that is part of the table
                if (startOid.IsRootOf(currentOid))
                {
                    //get every childOid start from startOID to currentOID
                    // if startOid = .1.1 and currentOid = .1.1.2.1 result will be [0] = 2 [1] = 1
                    uint[] currentChildOids = Oid.GetChildIdentifiers(startOid, currentOid);

                    //first column
                    if ((prevOid == startOid))
                    {
                        table.Add(new List <string>());
                        Oid columnOid = (Oid)startOid.Clone();
                        columnOid.Add(currentChildOids[0]);
                        columnOID.Add(columnOid.ToString());
                    }


                    //next columns
                    if (currentChildOids != null && prevChildOids != null)
                    {
                        //the first element is always name of column (new parameter in table)
                        if ((currentChildOids[0] > prevChildOids[0]))
                        {
                            //it means, currentOid is showing another column (parameter)
                            //adding another column!
                            table.Add(new List <string>());
                            Oid columnOid = (Oid)startOid.Clone();
                            columnOid.Add(currentChildOids[0]);
                            columnOID.Add(columnOid.ToString());
                        }
                    }

                    //saving the values
                    table[table.Count - 1].Add(localResult.Pdu.VbList[0].Value.ToString());
                }
                else
                {
                    // We've reached the end of the table. No point continuing the loop
                    //wychodzi z pętli tylko wtedy, gdy wyszlismy poza korzeń czyli długość curOid jest taka sama jak start i nie sa równe
                    break;
                }
            }//end of while

            /*
             * startOid - początkowe .1.0
             * prevOid - Oid z poprzedniego wywołania (służy do patrzenia, czy jesteśmy jeszcze w tej samej kolumnie czy już w nastepnej
             * currentOid - otrzymane OID z metody GetNext
             *
             * curOid musi zawierać całe startOid i być dłuższe aby while działał
             *
             */

            ShowTable(columnOID, table);
        }
示例#21
0
        /// <summary>SNMP WALK operation</summary>
        /// <remarks>
        /// When using SNMP version 1, walk is performed using GET-NEXT calls. When using SNMP version 2, 
        /// walk is performed using GET-BULK calls.
        /// </remarks>
        /// <example>Example SNMP walk operation using SNMP version 1:
        /// <code>
        /// String snmpAgent = "10.10.10.1";
        /// String snmpCommunity = "private";
        /// SimpleSnmp snmp = new SimpleSnmp(snmpAgent, snmpCommunity);
        /// Dictionary&lt;Oid, AsnType&gt; result = snmp.Walk(SnmpVersion.Ver1, "1.3.6.1.2.1.1");
        /// if( result == null ) {
        ///   Console.WriteLine("Request failed.");
        /// } else {
        /// foreach (KeyValuePair&lt;Oid, AsnType&gt; entry in result)
        /// {
        ///   Console.WriteLine("{0} = {1}: {2}", entry.Key.ToString(), SnmpConstants.GetTypeName(entry.Value.Type),
        ///     entry.Value.ToString());
        /// }
        /// </code>
        /// Will return:
        /// <code>
        /// 1.3.6.1.2.1.1.1.0 = OctetString: "Dual core Intel notebook"
        /// 1.3.6.1.2.1.1.2.0 = ObjectId: 1.3.6.1.9.233233.1.1
        /// 1.3.6.1.2.1.1.3.0 = TimeTicks: 0d 0h 0m 1s 420ms
        /// 1.3.6.1.2.1.1.4.0 = OctetString: "*****@*****.**"
        /// 1.3.6.1.2.1.1.5.0 = OctetString: "milans-nbook"
        /// 1.3.6.1.2.1.1.6.0 = OctetString: "Developer home"
        /// 1.3.6.1.2.1.1.8.0 = TimeTicks: 0d 0h 0m 0s 10ms
        /// </code>
        /// 
        /// To use SNMP version 2, change snmp.Set() method call first parameter to SnmpVersion.Ver2.
        /// </example>
        /// <param name="version">SNMP protocol version. Acceptable values are SnmpVersion.Ver1 and 
        /// SnmpVersion.Ver2</param>
        /// <param name="rootOid">OID to start WALK operation from. Only child OIDs of the rootOid will be
        /// retrieved and returned</param>
        /// <param name="tryGetBulk">this param is used to use get bulk on V2 requests</param>
        /// <returns>Oid => AsnType value mappings on success, empty dictionary if no data was found or
        /// null on error</returns>
        public Dictionary<Oid, AsnType> Walk(bool tryGetBulk, SnmpVersion version, string rootOid)
        {
            if (!Valid)
            {
                if (!_suppressExceptions)
                {
                    throw new SnmpException("SimpleSnmp class is not valid.");
                }
                return null;
            }
            // function only works on SNMP version 1 and SNMP version 2 requests
            if (version != SnmpVersion.Ver1 && version != SnmpVersion.Ver2)
            {
                if (!_suppressExceptions)
                {
                    throw new SnmpInvalidVersionException("SimpleSnmp support SNMP version 1 and 2 only.");
                }
                return null;
            }
            if (rootOid.Length < 2)
            {
                if (!_suppressExceptions)
                {
                    throw new SnmpException(SnmpException.InvalidOid, "RootOid is not a valid Oid");
                }
                return null;
            }
            Oid root = new Oid(rootOid);
            if (root.Length <= 0)
            {
                return null; // unable to parse root oid
            }
            Oid lastOid = (Oid)root.Clone();

            Dictionary<Oid, AsnType> result = new Dictionary<Oid, AsnType>();
            while (lastOid != null && root.IsRootOf(lastOid))
            {
                Dictionary<Oid, AsnType> val = null;
                if (version == SnmpVersion.Ver1)
                {
                    val = GetNext(version, new string[] { lastOid.ToString() });
                }
                else
                {
                    if (tryGetBulk == true)
                    {
                        val = GetBulk(new string[] { lastOid.ToString() });
                    }
                    else
                    {
                        val = GetNext(version, new string[] { lastOid.ToString() });
                    }
                }
                // check that we have a result
                if (val == null)
                {
                    // error of some sort happened. abort...
                    return null;
                }
                foreach (KeyValuePair<Oid, AsnType> entry in val)
                {
                    if (root.IsRootOf(entry.Key))
                    {
                        if (result.ContainsKey(entry.Key))
                        {
                            if (result[entry.Key].Type != entry.Value.Type)
                            {
                                throw new SnmpException(SnmpException.OidValueTypeChanged, "OID value type changed for OID: " + entry.Key.ToString());
                            }
                            else
                                result[entry.Key] = entry.Value;
                        }
                        else
                        {
                            result.Add(entry.Key, entry.Value);
                        }
                        lastOid = (Oid)entry.Key.Clone();
                    }
                    else
                    {
                        // it's faster to check if variable is null then checking IsRootOf
                        lastOid = null;
                        break;
                    }
                }
            }
            return result;
        }
示例#22
0
        public List <Host> SNMPWalk(string inOID)
        {
            List <Host> hosts = new List <Host>();

            Oid rootOid = new Oid(inOID);
            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);
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                string s = Regex.Replace(v.Oid.ToString(), "(" + inOID + ".)|((Integer32))", String.Empty);
                                hosts.Add(new Host(v.Oid.ToString(), v.Value.ToString()));
                                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
                            {
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(hosts);
        }
示例#23
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);
                    }
                }
            }
        }
示例#24
0
文件: Form1.cs 项目: shakasi/coding
        private void button11_Click(object sender, EventArgs e)
        {
            //SnmpTest snt = new SnmpTest(tbAddress.Text, "public", ".1.3.6.1.4.1.38446");
            //string[] t=  {".1.3.6.1.4.1.38446"};
            //snt.Test();



            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            param.Version = SnmpVersion.Ver2;
            IpAddress agent  = new IpAddress("192.168.1.120");
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu2 = new Pdu(PduType.GetBulk);

            pdu2.VbList.Add(".1.3.6.1.4.1.38446.1.1.2.1.13");

            SnmpV2Packet result2 = (SnmpV2Packet)target.Request(pdu2, param);

            int i = result2.Pdu.VbCount;

            string str  = SnmpConstants.GetTypeName(result2.Pdu.VbList[0].Value.Type);
            string str2 = result2.Pdu.VbList[0].Value.ToString();

            return;



            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(".1.3.6.1.4.1.38446.1.5.9.1.9"); // 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());
                                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.Dispose();
        }
示例#25
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);
        }
示例#26
0
 public static void GetTable()
 {
     Dictionary<String, Dictionary<uint, AsnType>> result = new Dictionary<String, Dictionary<uint, AsnType>>();
     // 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>();
     // Prepare agent information
     AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString("public"));
     IpAddress peer = new IpAddress("192.168.15.42");
     if (!peer.Valid)
     {
         Console.WriteLine("Unable to resolve name or error in address for peer: {0}", "");
         return;
     }
     UdpTarget target = new UdpTarget((IPAddress)peer);
     // This is the table OID supplied on the command line
     Oid startOid = new Oid("1.3.6.1.2.1.47.1.1.1");
     // Each table OID is followed by .1 for the entry OID. Add it to the table OID
     startOid.Add(1); // Add Entry OID to the end of the table OID
                      // Prepare the request PDU
     Pdu bulkPdu = Pdu.GetBulkPdu();
     bulkPdu.VbList.Add(startOid);
     // We don't need any NonRepeaters
     bulkPdu.NonRepeaters = 0;
     // Tune MaxRepetitions to the number best suited to retrive the data
     bulkPdu.MaxRepetitions = 100;
     // Current OID will keep track of the last retrieved OID and be used as
     //  indication that we have reached end of table
     Oid curOid = (Oid)startOid.Clone();
     // Keep looping through results until end of table
     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;
         }
         // For GetBulk request response has to be version 2
         if (res.Version != SnmpVersion.Ver2)
         {
             Console.WriteLine("Received wrong SNMP version response packet.");
             target.Close();
             return;
         }
         // Check if there is an agent error returned in the reply
         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;
         }
         // Go through the VbList and check all replies
         foreach (Vb v in res.Pdu.VbList)
         {
             curOid = (Oid)v.Oid.Clone();
             // VbList could contain items that are past the end of the requested table.
             // Make sure we are dealing with an OID that is part of the table
             if (startOid.IsRootOf(v.Oid))
             {
                 // Get child Id's from the OID (past the table.entry sequence)
                 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 (!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
             {
                 // We've reached the end of the table. No point continuing the loop
                 break;
             }
         }
         // If last received OID is within the table, build next request
         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
     {
         Console.Write("Instance");
         foreach (uint column in tableColumns)
         {
             Console.Write("\tColumn id {0}", column);
         }
         Console.WriteLine("");
         foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in result)
         {
             Console.Write("{0}", kvp.Key);
             foreach (uint column in tableColumns)
             {
                 if (kvp.Value.ContainsKey(column))
                 {
                     Console.Write("\t{0} ({1})", kvp.Value[column].ToString(),
                                       SnmpConstants.GetTypeName(kvp.Value[column].Type));
                 }
                 else
                 {
                     Console.Write("\t-");
                 }
             }
             Console.WriteLine("");
         }
     }
 }
示例#27
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();
        }
示例#28
0
        private List <SnmpResult <int, long> > ProcessTargetsTraffic(SnmpTarget snmpTarget, string snmpOid,
                                                                     string communityString = "public")
        {
            var results = new List <SnmpResult <int, long> >();

            var community = new OctetString(communityString);
            var param     = new AgentParameters(community)
            {
                Version = SnmpVersion.Ver2
            };
            var agent   = new IpAddress(snmpTarget.IpAddress);
            var target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
            var rootOid = new Oid(snmpOid);
            var lastOid = (Oid)rootOid.Clone();
            var pdu     = new Pdu(PduType.GetBulk)
            {
                NonRepeaters = 0, MaxRepetitions = 5
            };

            while (lastOid != null)
            {
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                pdu.VbList.Clear();
                pdu.VbList.Add(lastOid);
                var result = (SnmpV2Packet)target.Request(pdu, param);

                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        break;
                    }

                    foreach (var v in result.Pdu.VbList)
                    {
                        var current = new SnmpResult <int, long>();

                        if (rootOid.IsRootOf(v.Oid))
                        {
                            Console.WriteLine("{0} ({1}): {2}",
                                              v.Oid,
                                              SnmpConstants.GetTypeName(v.Value.Type),
                                              v.Value);

                            current.Result     = Convert.ToInt64(v.Value.ToString());
                            current.Identifier = Convert.ToInt32(v.Oid.ToString().Split('.').Last());
                            current.Oid        = v.Oid.ToString();
                            current.SnmpTarget = snmpTarget;

                            results.Add(current);

                            lastOid = v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW ? null : v.Oid;
                        }
                        else
                        {
                            lastOid = null;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();

            return(results);
        }
示例#29
0
        private void cbbSelectEquip_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Equipment equip     = (sender as ComboBox).SelectedItem as Equipment;
            string    equipName = equip.Name;
            int       equipID   = equip.Index;
            IpAddress agentIP   = null;

            try
            {
                object strIP = App.DBHelper.returnScalar(string.Format("SELECT IP_Address FROM IPAddress WHERE(IP_EquipID = {0}) AND (IP_IsDefaultIP = 1)", equipID));
                if (strIP == null)
                {
                    MessageBox.Show("数据库中没有" + equipName + "的默认管理IP地址");
                    return;
                }
                if (IpAddress.IsIP(strIP.ToString()))
                {
                    agentIP = new IpAddress(strIP.ToString());
                }
                else
                {
                    MessageBox.Show("地址格式错误");
                    return;
                }
            }
            catch
            {
                MessageBox.Show("读取数据库出现错误\n" + e.ToString());
            }

            OctetString     community = new OctetString("public");
            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 target
            UdpTarget target = new UdpTarget((IPAddress)agentIP, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid1 = new Oid("1.3.6.1.2.1.2.2.1.1"); // ifIndex
            Oid rootOid2 = new Oid("1.3.6.1.2.1.2.2.1.2"); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid1 = (Oid)rootOid1.Clone();
            Oid lastOid2 = (Oid)rootOid2.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 (lastOid1 != null && lastOid2 != 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(lastOid1);
                pdu.VbList.Add(lastOid2);
                // 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);
                        MessageBox.Show(string.Format("SNMP应答数据包中有错误。 Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex));
                        lastOid1 = null;
                        lastOid2 = 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 (rootOid1.IsRootOf(v.Oid))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid1 = null;
                                }
                                else
                                {
                                    lastOid1 = v.Oid;
                                }
                                var f = v.Value;
                                //Interface interface = new Interface(v.Value.,)
                            }
                            else if (rootOid2.IsRootOf(v.Oid))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid2 = null;
                                }
                                else
                                {
                                    lastOid2 = v.Oid;
                                }
                                var f = v.Value;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid1 = null;
                                lastOid2 = null;
                            }



//                             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();
        }
示例#30
0
        private void button11_Click(object sender, EventArgs e)
        {
            //SnmpTest snt = new SnmpTest(tbAddress.Text, "public", ".1.3.6.1.4.1.38446");
            //string[] t=  {".1.3.6.1.4.1.38446"};
            //snt.Test();

            


            OctetString community = new OctetString("public");
            AgentParameters param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver2;
            IpAddress agent = new IpAddress("192.168.1.120");
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu2 = new Pdu(PduType.GetBulk);
            pdu2.VbList.Add(".1.3.6.1.4.1.38446.1.1.2.1.13");

            SnmpV2Packet result2 = (SnmpV2Packet)target.Request(pdu2, param);

            int i=result2.Pdu.VbCount;
            
            string str= SnmpConstants.GetTypeName(result2.Pdu.VbList[0].Value.Type);
            string str2 = result2.Pdu.VbList[0].Value.ToString();
            return;











            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(".1.3.6.1.4.1.38446.1.5.9.1.9"); // 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());
                                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.Dispose();
        }
示例#31
0
        public void pobierzTabeleDoUsuniecia()
        {
            /*! 
		     *Pobiera tabele SNMP.
             */
            Dictionary<String, Dictionary<uint, AsnType>> tabela_rezultat = new Dictionary<string, Dictionary<uint, AsnType>>();
            List<uint> tabeleKolumy = new List<uint>();
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
            IpAddress peer = new IpAddress(host);
            if (!peer.Valid)
            {
                Console.WriteLine("Zły adres.");
                return;
            }

            UdpTarget target = new UdpTarget((IPAddress)peer);
            Oid startOid = new Oid("1.3.6.1.2.1.6.13");
            startOid.Add(1);

            //przygotowanie zapytania
            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("Zapytanie nieudane {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 zwrócił błąd {0} dla zapytania {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 (!tabeleKolumy.Contains(column))
                            tabeleKolumy.Add(column);
                        if (tabela_rezultat.ContainsKey(strInst))
                        {
                            tabela_rezultat[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            tabela_rezultat[strInst] = new Dictionary<uint, AsnType>();
                            tabela_rezultat[strInst][column] = (AsnType)v.Value.Clone();
                        }
                    }
                    else
                    {
                        break; //bo koniec tabeli ;)
                    }
                }
                if (startOid.IsRootOf(curOid))
                {
                    bulkPdu.VbList.Clear();
                    bulkPdu.VbList.Add(curOid);
                    bulkPdu.NonRepeaters = 0;
                    bulkPdu.MaxRepetitions = 100;
                }
                target.Close();
                if (tabela_rezultat.Count <= 0)
                {
                    Console.WriteLine("Żadnych rezlutatów nie zwrócono");
                }
                else
                {
                    Console.WriteLine("Instance");
                    foreach (uint column in tabeleKolumy)
                    {
                        Console.Write("\tColumn id {0}", column);
                    }
                    Console.WriteLine("");
                    foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in tabela_rezultat)
                    {
                        Console.Write("{0}", kvp.Key);
                        foreach (uint column in tabeleKolumy)
                        {
                            if (kvp.Value.ContainsKey(column))
                            {
                                Console.Write("\t{0} ({1})", kvp.Value[column].ToString(), SnmpConstants.GetTypeName(kvp.Value[column].Type));
                            }
                            else
                            {
                                Console.Write("\t-");
                            }
                        }
                        Console.WriteLine("");
                    }
                }
            }
        }
示例#32
0
        public PartialViewResult WalkSend(int?page, string presetName, string TowerName, string IP, string DeviceName)
        {
            Checked.Clear();
            Time.Clear();
            walkSearch.Clear();
            SearchNameWalk = "";

            if (presetName == "Preset")
            {
                PresetIND = 0;
                walkList.Clear();
                IPadrress  = IP;
                ViewBag.IP = IPadrress;

                //var devicename = db.devicesTypes.Where(d => d.Name == DeviceName).FirstOrDefault();
                //var walkOid = db.MibTreeInformations.Where(m => m.DeviceID == devicename.ID).FirstOrDefault();
                //deviceTypeID = devicename.ID;
                OctetString community = new OctetString("public");

                AgentParameters param = new AgentParameters(community);
                param.Version = SnmpVersion.Ver2;

                IpAddress agent = new IpAddress("192.168.24.12");

                UdpTarget target  = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Oid       rootOid = new Oid(".1.3.6.1.4.1"); // ifDescr
                                                             //Oid rootOid = new Oid(".1.3.6.1.4.1.23180.2.1.1.1"); // ifDescr

                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);
                        SnmpV2Packet 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))
                                    {
                                        WalkDevice walk = new WalkDevice();
                                        ID++;
                                        walk.ID     = ID;
                                        walk.WalkID = ID;
                                        string oid = "." + v.Oid.ToString();
                                        var    OidMibdescription = db.MibTreeInformations.Where(m => m.OID == oid).FirstOrDefault();
                                        if (OidMibdescription == null)
                                        {
                                            oid = oid.Remove(oid.Length - 1);
                                            oid = oid.Remove(oid.Length - 1);
                                            OidMibdescription = db.MibTreeInformations.Where(o => o.OID == oid).FirstOrDefault();
                                        }
                                        if (OidMibdescription == null)
                                        {
                                            oid = oid.Remove(oid.Length - 1);
                                            oid = oid.Remove(oid.Length - 1);
                                            OidMibdescription = db.MibTreeInformations.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;
                                        }

                                        walk.WalkOID = v.Oid.ToString();
                                        walk.Type    = v.Value.ToString();
                                        walk.value   = SnmpConstants.GetTypeName(v.Value.Type);
                                        walk.Time    = 60;
                                        walkList.Add(walk);
                                        lastOid = v.Oid;
                                    }
                                    else
                                    {
                                        lastOid = null;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e) { }
                }

                target.Close();
            }
            else
            {
                var presetname = db.Presets.Where(p => p.PresetName == presetName).FirstOrDefault();
                walkList = db.WalkDevices.Where(w => w.PresetID == presetname.ID).ToList();
            }

            //for (int i = 0; i < 120; i++)
            //{
            //    WalkInformation walk = new WalkInformation();
            //    ID++;
            //    walk.ID = ID;
            //    walk.OIDName = "1.2.2.3.50.20.21.2.2.3.50.20.21.2.2.3.50.20.21.2.2.3.50.20.2";
            //    walk.Value = "mrt_____mrt_____mrt_____mrt_____mrt_____mrt_____";
            //    walk.Time = 60;
            //    walkList.Add(walk);
            //}
            EditInd      = 0;
            ViewBag.Edit = EditInd;
            return(PartialView("_WalkView", walkList.ToPagedList(page ?? 1, viewSearch)));
        }
示例#33
0
        public Tabela pobierzTabele()
        {
            /*! 
		     *Pobiera tabele SNMP.
             */
            Tabela tabela1 = new Tabela();
            AgentParameters param = new AgentParameters(SnmpVersion.Ver2, new OctetString(community));
            IpAddress peer = new IpAddress(host);
            if (!peer.Valid)
            {
                Console.WriteLine("Zły adres.");
                //return false;
            }
            UdpTarget target = new UdpTarget((IPAddress)peer);
            Oid startOid = new Oid("1.3.6.1.2.1.6.13");
            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("Zapytanie nieudane {0}", ex.Message);
                    target.Close();
                    //return false;
                }
                if (res.Version != SnmpVersion.Ver2)
                {
                    Console.WriteLine("Otrzymano inną wersję SNMP w odpowiedzi.");
                    target.Close();
                    //return false;
                }
                if (res.Pdu.ErrorStatus != 0)
                {
                    Console.WriteLine("SNMP agent zwrócił błąd {0} dla zapytania {1}", res.Pdu.ErrorStatus, res.Pdu.ErrorIndex);
                    target.Close();
                    //return false;
                }
                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 (!tabelaKolumn.Contains(column))
                            tabelaKolumn.Add(column);
                        if (slownikRezultatu.ContainsKey(strInst))
                        {
                            slownikRezultatu[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else {
                            slownikRezultatu[strInst] = new Dictionary<uint, AsnType>();
                            slownikRezultatu[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 (slownikRezultatu.Count <= 0)
            {
                //Console.WriteLine("Żadnych rezlutatów nie zwrócono");
                //return false;
            }
            else {
                //return true;
            }

            /*UFAM W TABELE, ŻE SŁOWNIK NIE ODWRÓCI KOLEJNOŚCI I WALĘ NA OŚLEP KOLEJNE WARTOŚCI*/
            foreach (KeyValuePair<string, Dictionary<uint, AsnType>> kvp in slownikRezultatu)
            {
                int i = 0;
                tabela1.tcpAddress.Add(kvp.Key);
                foreach (uint kolumna in tabelaKolumn)
                {
                    if (kvp.Value.ContainsKey(kolumna))
                    {
                        if (i == 0)
                            tabela1.tcpConnLocalAddress.Add(kvp.Value[kolumna].ToString());
                        else if (i == 1)
                            tabela1.tcpConnLocalPort.Add(kvp.Value[kolumna].ToString());
                        else if (i == 2)
                            tabela1.tcpConnRemAddress.Add(kvp.Value[kolumna].ToString());
                        else if (i == 3)
                            tabela1.tcpConnRemPort.Add(kvp.Value[kolumna].ToString());
                        else if (i == 4)
                            tabela1.tcpConnState.Add(kvp.Value[kolumna].ToString());

                        i++;
                    }
                }
            }

            /*/BUDOWA DRZEWA
            foreach (KeyValuePair<string,Dictionary<uint,AsnType>> kvp in slownikRezultatu)
            {
                tabela1.tcpAddress.Add(kvp.Key);
                tabela1.tcpConnLocalAddress.Add(kvp.Value[0].ToString());
                tabela1.tcpConnLocalPort.Add(kvp.Value[1].ToString());
                tabela1.tcpConnRemAddress.Add(kvp.Value[2].ToString());
                tabela1.tcpConnRemPort.Add(kvp.Value[3].ToString());
                tabela1.tcpConnState.Add(kvp.Value[4].ToString());
            }*/
            return tabela1;
        }
示例#34
0
        //v2の時
        private int getBulk(AgentParameters param, Form_snmpDataGet form)
        {
            try {
                int ret = 0;
                //結果格納
                resultHashL = new List <Dictionary <string, string> >();
                _headerList = new List <string>();

                tablearray = new Dictionary <string, List <string> >();



                int       flg   = 0;
                IpAddress agent = new IpAddress(INPUT.hostname);

                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 5000, 1);                       // アドレス ポート 待ち時間 リトライ

                Oid rootOid = new Oid(INPUT.oid);

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

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


                pdu.NonRepeaters = 0;

                pdu.MaxRepetitions = 50;

                // Loop through results
                while (lastOid != null)
                {
                    System.Windows.Forms.Application.DoEvents();

                    if (form.cancelflg)
                    {
                        //中断された時
                        form.cancelflg = false;
                        break;
                    }

                    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
                    System.Threading.Thread.Sleep(15);
                    SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                    //Console.WriteLine("{0}  {1}  ", result.Pdu.ErrorStatus,result.Pdu.ErrorIndex);

                    // 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
                            Errormsg = string.Format("Error in SNMP reply. Error {0} index {1}",
                                                     result.Pdu.ErrorStatus,
                                                     result.Pdu.ErrorIndex);
                            lastOid = null;
                            ret     = -1;
                            break;
                        }
                        else
                        {
                            int i = 0;
                            // 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))
                                {
                                    //tableget
                                    //値の取得
                                    Dictionary <string, string> hashtbl = new Dictionary <string, string>();

                                    if (INPUT.method == 3)
                                    {
                                        //テーブル用データの取得
                                        getForTable(v, ref flg);
                                    }
                                    else
                                    {
                                        hashtbl["oid"]  = v.Oid.ToString();
                                        hashtbl["type"] = SnmpConstants.GetTypeName(v.Value.Type);

                                        //ifdescの時日本語の可能性あり
                                        //1.3.6.1.2.1.2.2.1.2 ifdesc
                                        //1.3.6.1.2.1.25.3.2.1.3. hrDeviceDescr
                                        if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2.") | 0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3."))
                                        {
                                            hashtbl["value"] = convertJP(v.Value.ToString());
                                        }
                                        else
                                        {
                                            if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.3."))
                                            {
                                                hashtbl["value"] = Util.ifTypeConv(v.Value.ToString());
                                            }
                                            else if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8."))
                                            {
                                                hashtbl["value"] = Util.convIfStatus(v.Value.ToString());
                                            }
                                            else
                                            {
                                                string value = v.Value.ToString();

                                                //TimeTick型の時はミリ秒も出力する
                                                if (hashtbl["type"] == SnmpConstants.SMI_TIMETICKS_STR)
                                                {
                                                    TimeTicks timeti = (TimeTicks)v.Value;
                                                    value = "(" + timeti.Milliseconds.ToString() + "ms)" + v.Value.ToString();
                                                }
                                                hashtbl["value"] = value;
                                            }
                                        }

                                        //リストに格納
                                        resultHashL.Add(hashtbl);
                                    }
                                    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;
                                }
                                i++;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No response received from SNMP agent.");
                    }
                }
                target.Close();
                return(ret);
            }
            catch {
                throw;
            }
        }
示例#35
0
        public static void SNMPTestConcepto()
        {
            int _NumEntries = 0;

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

            // 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
            //Oid rootOid = new Oid("1.3.6.1.2.1.17.4.3.1"); // conexiones bridge
            Oid rootOid = new Oid("1.3.6.1.2.1"); // TEST

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

                                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();
            Console.WriteLine("Número entradas: {0}", _NumEntries);
        }
示例#36
0
        /// <summary>
        /// Walks an SNMP mib table displaying the results on the fly (unless otherwise desired)
        /// </summary>
        /// <param name="log_options">Logging options</param>
        /// <param name="ip">IPAddress of device to walk</param>
        /// <param name="in_community">Read-community of device to walk</param>
        /// <param name="start_oid">Start OID (1.3, etc)</param>
        /// <returns></returns>
        public static List<SnmpV1Packet> MibWalk(LOG_OPTIONS log_options, IPAddress ip, string in_community, string start_oid)
        {
            stop = false;
            List<SnmpV1Packet> packets = new List<SnmpV1Packet>();
            // SNMP community name
            OctetString community = new OctetString(in_community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 1
            param.Version = SnmpVersion.Ver1;

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

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid(start_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;
                }
                if (stop)
                {
                    return packets;
                }
                // 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
                    packets.Add(result);
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus + " index " + 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))
                            {
                                Logger.Write(log_options, module, v.Oid.ToString() + " " + SnmpConstants.GetTypeName(v.Value.Type) + ": " + 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 packets;
        }
示例#37
0
        public void GetTable(string OID)
        {
            this.param.Version = SnmpVersion.Ver2;
            Oid startOid = new Oid(OID);

            startOid.Add(1);
            Console.WriteLine(startOid);
            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 (results.ContainsKey(strInst))
                        {
                            results[strInst][column] = (AsnType)v.Value.Clone();
                        }
                        else
                        {
                            results[strInst]         = new Dictionary <uint, AsnType>();
                            results[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;
                }
            }
        }
示例#38
0
        public static void TestOidCollection()
        {
            int           i;
            OidCollection c = new OidCollection();

            Assert.Equal(0, c.Count);

            Oid o0 = new Oid(SHA1_Oid, SHA1_Name);

            i = c.Add(o0);
            Assert.Equal(0, i);

            Oid o1 = new Oid(SHA256_Oid, SHA256_Name);

            i = c.Add(o1);
            Assert.Equal(1, i);

            Assert.Equal(2, c.Count);

            Assert.Same(o0, c[0]);
            Assert.Same(o1, c[1]);
            Assert.Throws <ArgumentOutOfRangeException>(() => GC.KeepAlive(c[-1]));
            Assert.Throws <ArgumentOutOfRangeException>(() => GC.KeepAlive(c[c.Count]));

            Oid o2 = new Oid(SHA1_Oid, SHA1_Name);

            i = c.Add(o2);
            Assert.Equal(2, i);

            // If there multiple matches, the one with the lowest index wins.
            Assert.Same(o0, c[SHA1_Name]);
            Assert.Same(o0, c[SHA1_Oid]);

            Assert.Same(o1, c[SHA256_Name]);
            Assert.Same(o1, c[SHA256_Oid]);

            Oid o3 = new Oid(null, null);

            i = c.Add(o3);
            Assert.Equal(3, i);
            Assert.Throws <ArgumentNullException>(() => GC.KeepAlive(c[null]));

            Object o = c["BOGUSBOGUS"];

            Assert.Null(c["BOGUSBOGUS"]);

            Oid[] a = new Oid[10];
            for (int j = 0; j < a.Length; j++)
            {
                a[j] = new Oid(null, null);
            }
            Oid[] a2 = (Oid[])(a.Clone());

            c.CopyTo(a2, 3);
            Assert.Equal(a[0], a2[0]);
            Assert.Equal(a[1], a2[1]);
            Assert.Equal(a[2], a2[2]);
            Assert.Equal(o0, a2[3]);
            Assert.Equal(o1, a2[4]);
            Assert.Equal(o2, a2[5]);
            Assert.Equal(o3, a2[6]);
            Assert.Equal(a[7], a2[7]);
            Assert.Equal(a[8], a2[8]);
            Assert.Equal(a[9], a2[9]);

            Assert.Throws <ArgumentNullException>(() => c.CopyTo(null, 0));
            Assert.Throws <ArgumentNullException>(() => c.CopyTo(null, -1));
            Assert.Throws <ArgumentOutOfRangeException>(() => c.CopyTo(a, -1));
            Assert.Throws <ArgumentException>(() => c.CopyTo(a, 7));
            Assert.Throws <ArgumentOutOfRangeException>(() => c.CopyTo(a, 1000));

            ICollection ic = c;

            Assert.Throws <ArgumentException>(() => ic.CopyTo(new Oid[4, 3], 0));
            Assert.Throws <InvalidCastException>(() => ic.CopyTo(new string[100], 0));

            return;
        }
示例#39
0
        public SNMPResultSet[] Walk(string pOID)
        {
            List <SNMPResultSet> snmpResults = new List <SNMPResultSet>();

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

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

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

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

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

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

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

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

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

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

            return(snmpResults.ToArray());
        }
示例#40
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);
        }
示例#41
-1
 /// <summary>
 /// Construct Vb with the supplied OID and Null value
 /// </summary>
 /// <param name="oid">OID</param>
 public Vb(Oid oid)
     : this()
 {
     _oid = (Oid)oid.Clone();
     _value = new Null();
 }