snmp获取服务器信息

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using SnmpSharpNet;
using System.IO;
using System.Net;
using System.Collections;
using System.Configuration;

namespace GWMC
{
    /// <summary>
    /// 采用snmp获取服务器的运行信息
    /// </summary>
    internal class SnmpShartNet
    {

        /// <summary>
        /// 服务器的IP
        /// </summary>
        string s_ip = string.Empty;

        /// <summary>
        /// 请求等待的时间(毫秒)
        /// </summary>
        int s_time = 2000;

        /// <summary>
        /// 获取信息的oid
        /// </summary>
        string s_irootOid = string.Empty;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ip">服务器IP</param>
        /// <param name="irootOid">OID</param>
        public SnmpShartNet(string ip, string irootOid)
        {
            this.s_ip = ip;
            this.s_irootOid = irootOid;
        }

        /// <summary>
        /// 用snmp协议获取数据
        /// </summary>
        internal SnmpV2Packet GetInfo()
        {
            lock (this)
            {
                try
                {

                    Dictionary<string, string> dictionary = Command.JsonToDictionary(s_irootOid);
                    string trapName = null;
                    if (!dictionary.TryGetValue("moni0", out trapName))
                    {
                        return null;
                    }
                    // SNMP community name
                    OctetString community = new OctetString(trapName);

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

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

                    Pdu pdu = new Pdu(PduType.Get);

                    foreach (KeyValuePair<string, string> item in dictionary)
                    {
                        if (item.Key != "moni0")
                        {
                            pdu.VbList.Add(item.Value.ToString());
                        }
                    }

                    // Make SNMP request
                    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)
                        {
                            Command.WriteLog(string.Format("Error in SNMP reply. Error {0} index {1} \r\n", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex));
                        }
                        else
                        {
                            return result;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Command.WriteLog(ex.Message);
                }
                return null;
            }
        }

        /// <summary>
        /// 根据oid的根节点判断子节点中是否有要找的值
        /// </summary>
        /// <param name="processName">要找的值</param>
        /// <returns>Boolean</returns>
        internal Command.MonitorState IsProcessLive(string processName, int processCount)
        {
            lock (this)
            {
                try
                {
                    int count = 0;
                    Dictionary<string, string> dictionary = Command.JsonToDictionary(s_irootOid);

                    string trapName = string.Empty;
                    if (!dictionary.TryGetValue("moni0", out trapName))
                    {
                        return Command.MonitorState.nothing;
                    }

                    OctetString community = new OctetString(trapName);

                    AgentParameters param = new AgentParameters(community);
                    param.Version = SnmpVersion.Ver2;
                    IpAddress agent = new IpAddress(s_ip);
                    UdpTarget target = new UdpTarget((IPAddress)agent, 161, s_time, 1);

                    string irootOid = null;
                    if (!dictionary.TryGetValue("moni1", out irootOid))
                    {
                        return Command.MonitorState.nothing;
                    }

                    Oid rootOid = new Oid(irootOid);

                    Oid lastOid = (Oid)rootOid.Clone();
                    Pdu pdu = new Pdu(PduType.GetBulk);
                    pdu.NonRepeaters = 0;
                    pdu.MaxRepetitions = 10;

                    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)
                            {
                                // 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.ToString().Equals(processName,StringComparison.InvariantCultureIgnoreCase))
                                            count++;
                                        lastOid = v.Oid;
                                    }
                                    else
                                        lastOid = null;
                                }
                            }
                        }
                    }
                    return (count == processCount) ? Command.MonitorState.normal : Command.MonitorState.warning;
                }
                catch (Exception ex)
                {
                    Command.WriteLog(ex.Message.ToString());
                    return Command.MonitorState.nothing;
                }
            }
        }
    }
}

 

posted @ 2012-07-10 17:03  小风。  阅读(1573)  评论(0编辑  收藏  举报