Saturday, December 18, 2010

Finding the percentage of CPU Utilization on a Cisco Router using SNMP

This segment of code uses SNMP and .NET to find the CPU Utilization and displays on a circle graph.  You have to use the previous SNMP Class in which I had listed in an earlier Blog.  Be sure to reference the DLL in the beginning assembly declarations.  This displays the Utilization in percentage:



public void CiscoRouterConnect(string arg0,
    string arg1)
    {
        Label1.ForeColor = Color.Black;
        ChartSpace.ImageUrl = "images/100.png";


        ChartSpace.Visible = true;
        Label1.Text = "Sorry! Router could not be found!";
        Label1.ForeColor = Color.Black;
        this.Label1.Style["text-align"] = "left";


        int commlength, miblength, datastart, cpuUtil;


        SNMP conn = new SNMP();
        byte[] response = new byte[1024];


        Label1.Text = "<br />Router <b>" + arg0 +
            "</b> CPU information: <br />";
        Label1.Text +=
            "----------------------------------------------<br />";


        try
        {
            // Send SNMP request for Router CPU utilization
            response = conn.get("get", arg0, arg1, "1.3.6.1.4.1.9.2.1.58.0");
            if (response[0] == 0xff)
            {
                Label1.Text += "No response from " + arg0 + "<br />";
                return;
            }
            DateTime time;


            commlength = Convert.ToInt16(response[6]);
            miblength = Convert.ToInt16(response[23 + commlength]);
            datastart = 26 + commlength + miblength;
            cpuUtil = Convert.ToInt16(response[datastart]);
            time = DateTime.Now;


            long free2 = (100 - Convert.ToInt64(100 - (((cpuUtil)) * 100)));
            double free = 100 - (Math.Round(free2 / 5.0) * 5);
            ChartSpace.Visible = true;
            ChartSpace.ImageUrl = "images/" + free.ToString() + ".png";


            Label1.Text += time + "<b> - Utilization CPU: </b>" +
                  cpuUtil + " %<br />";
        }
        catch (Exception ex)
        {
            Label1.ForeColor = Color.Maroon;
       
            Label1.Text = "Sorry! Router could not be found for <b>" + 
                txtServer.Text + "</b>. " + ex.Message;
            ChartSpace.ImageUrl = "images/100.png";


            ChartSpace.Visible = true;
        }
    }

No comments:

Post a Comment