C# 使用Zabbix API 获取监控设备CPU、内存、硬盘、网络数据

1.在 home控制器中添加 GetToken 方法,获取登录令牌。

 public JsonResult GetToken()
        {
            string url = "http://1.1.1.1:8086/zabbix/api_jsonrpc.php";
            
            Params @params = new Params() { user = "用户名", password = "密码" };
            GetToken getToken = new GetToken()
            {
                jsonrpc = "2.0",
                method = "user.login",
                @params = @params,
                id = 0,
                auth = null
            };
            var data = Newtonsoft.Json.JsonConvert.SerializeObject(getToken);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json-rpc";
            request.ProtocolVersion = new Version(1, 0);   //Http/1.0版本

            byte[] buffer = encoding.GetBytes(data);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                var result = reader.ReadToEnd();
                return Json(result);
            }
        }

GetToken实体类 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ZabbixTest.Models
{
    public class GetToken
    {
        public string jsonrpc { get; set; }

        public string method { get; set; }

        public Params @params { get; set; }

        public int id { get; set; }

        public string auth { get; set; }
    }

    public class Params
    {
        public  string user { get; set; }

        public string password { get; set; }
    }
}

2.在home控制器中创建 GetData()方法,用来获取各种数据。

public JsonResult GetData(string json)
        {
            string url = "http://1.1.1.1:8086/zabbix/api_jsonrpc.php";
           
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json-rpc";
            request.ProtocolVersion = new Version(1, 0);   //Http/1.0版本

            byte[] buffer = encoding.GetBytes(json);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                var result = reader.ReadToEnd();
                return Json(result);
            }

        }

3.修改index.cshtml,用于显示相关数据(没有则创建)。

@{
    ViewBag.Title = "Home Page";
    Layout = null;
}

<div>
    <input type="hidden" id="token" />
    <button value="获取登录" onclick="GetToken()">获取登录</button>
    <button value="获取设备" onclick="GetDevice()">获取设备</button>
    <select style="" id="service">
        <option value=""></option>
    </select>
    <button value="获取报警" onclick="GetDeviceAlert()">获取报警</button>
    <button value="获取模板" onclick="GetDeviceTemplateid()">获取模板</button>
    <button value="查看信息" onclick="GetDataInfo()">查看信息</button>
</div>
<div style="width:70%;height:300px;background-color:#000000;color:#ffffff;margin-top:30px;" id="showdata">
    <div id="dataTile" style="height:50px;line-height:50px;width:100%"></div>
    <div style="width:30%;height:auto;float:left" id="cpu"></div>
    <div style="width:30%;height:auto;float:left" id="memory"></div>
    <div style="width:30%;height:auto;float:left" id="fs"></div>
    <div style="width:100%;height:auto;float:left" id="net"></div>
</div>

<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Js/index.js"></script>

4.创建 index.js 获取相关数据。


var token = "";
//获取登录信息
function GetToken() {

    var data = {
       
    };

    $.ajax({
        type: "POST",
        url: "/Home/GetToken",
        data: data,
        dataType: "json",
        success: function (re) {
            var data = JSON.parse(re);
            console.log(data);
            token = data.result;
            $("#token").val(data.result);
            $("#dataTile").text(data.result);
        }
    });
}
//获取监控设备列表
function GetDevice() {
    var json = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": "extend",
        },
        "id": 1,
        "auth": $("#token").val()
    };

    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: { "json": JSON.stringify(json) },
        dataType: "json",
        async: false,
        success: function (re) {
            var data = $.parseJSON(re);
            console.log(data);
            if (data.result.length > 0) {
                var htmlstr = '';
                console.log(data.result);
                $.each(data.result, function (index, e) {
                    htmlstr += ' <option value="' + e.hostid + '">' + e.name + '</option>';
                });
                $("#service").html(htmlstr);
            }
        }
    });
    //$("#showdata").text(JSON.parse(data).result);

}
//获取警报
function GetDeviceAlert() {
    var json = {
        "jsonrpc": "2.0",
        "method": "alert.get",
        "params": {
            "output": "extend",
            "actionids": 0
        },
        "id": 1,
        "auth": $("#token").val()
    };

    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: { "json": JSON.stringify(json) },
        dataType: "json",
        async: false,
        success: function (re) {
            var data = $.parseJSON(re);
            console.log(data);

        }
    });
}
//获取监控项 
function GetDeviceTemplateid() {
    var hostid = $("#service").val();
   
//监控项的key 是 zabbix 中配置的 具体见下图
    //system.cpu.util[,user]  每分钟CPU使用率
    //vm.memory.size[pused]  内存
    //vfs.fs.size[/,pused] 硬盘
    //agent.ping  是否存活

//cpu 使用率
    var jsoncpu = {
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "itemids",
            "hostids": hostid,
            "search": {
                "key_": "system.cpu.util[,user]"
            }
        },
        "auth": $("#token").val(),
        "id": 1
    }

    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: { "json": JSON.stringify(jsoncpu) },
        dataType: "json",
        async: false,
        success: function (re) {
            var data = $.parseJSON(re);
            console.log(data);
            $.each(data.result, function (i, e) {
                GetDeviceInfo(e.itemid, "CPU 使用率", "cpu");
            });
        }
    });


//内存使用率
    var jsonmemory = {
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "itemids",
            "hostids": hostid,
            "search": {
                "key_": "vm.memory.size[pused]"
            }
        },
        "auth": $("#token").val(),
        "id": 1
    }

    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: { "json": JSON.stringify(jsonmemory) },
        dataType: "json",
        async: false,
        success: function (re) {
            var data = $.parseJSON(re);
            console.log(data);
            $.each(data.result, function (i, e) {
                GetDeviceInfo(e.itemid, "内存 使用率", "memory");
            });
        }
    });

//硬盘使用率
    var jsonfs = {
        "jsonrpc": "2.0",
        "method": "item.get",
        "params": {
            "output": "itemids",
            "hostids": hostid,
            "search": {
                "key_": "vfs.fs.size[/,pused]"
            }
        },
        "auth": $("#token").val(),
        "id": 1
    }

    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: { "json": JSON.stringify(jsonfs) },
        dataType: "json",
        async: false,
        success: function (re) {
            var data = $.parseJSON(re);
            console.log(data);
            $.each(data.result, function (i, e) {
                GetDeviceInfo(e.itemid, "硬盘 使用率", "fs");
            });
        }
    });

}
// 根据 监控项ID 获取监控数据
function GetDeviceInfo(itemids, name, idname) {
    var hostid = $("#service").val();
   

    var json = {
        "jsonrpc": "2.0",
        "method": "history.get",
        "params": {
            "output": "extend",
            "history": 0,
            "itemids": itemids,
            "sortfield": "clock",
            "sortorder": "DESC",
            "limit": 10
        },
        "auth": $("#token").val(),
        "id": 1
    };

    $.ajax({
        type: "POST",
        url: "/Home/GetData",
        data: { "json": JSON.stringify(json) },
        dataType: "json",
        async: false,
        success: function (re) {
            var data = $.parseJSON(re);
            console.log(data);
            $("#" + idname).html("");
            $("#" + idname).append(name + "</br>");
            $.each(data.result, function (i, e) {
                var date2 = timestampToTime(parseInt(e.clock));
                $("#" + idname).append("时间:" + date2);
                $("#" + idname).append("  使用率:" + e.value + "%</br>");
            });

        }
    });



}


function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}
//获取网路数据
function GetDataInfo() {
    var hostid = $("#service").val();
    var keys = ["net.if.in[ens192,bytes]", "net.if.out[ens192,bytes]", "net.if.total[ens192,bytes]"];
    var itemids = new Array();
    $.each(keys, function (i, item) {
        var jsonfs = {
            "jsonrpc": "2.0",
            "method": "item.get",
            "params": {
                "output": "itemids",
                "hostids": hostid,
                "search": {
                    "key_": item
                }
            },
            "auth": $("#token").val(),
            "id": 1
        }

        $.ajax({
            type: "POST",
            url: "/Home/GetData",
            data: { "json": JSON.stringify(jsonfs) },
            dataType: "json",
            async: false,
            success: function (re) {
                var data = $.parseJSON(re);
                console.log(data);
                $.each(data.result, function (i, e) {
                    itemids.push(e.itemid);
                });
            }
        });
    });
    GetNetInfo(itemids, "网络", "net");



}
//获取网络数据  并运算
function GetNetInfo(itemids, name, idname) {
    var netdatas = new Array();
    $.each(itemids, function (i, item) {
        var json = {
            "jsonrpc": "2.0",
            "method": "history.get",
            "params": {

                "itemids": [
                    item
                ],
                "limit": "10",
                "sortfield": "clock",
                "sortorder": "DESC",
            },
            "auth": $("#token").val(),
            "id": 1
        }

        
        $.ajax({
            type: "POST",
            url: "/Home/GetData",
            data: { "json": JSON.stringify(json) },
            dataType: "json",
            async: false,
            success: function (re) {
                var data = $.parseJSON(re);
                var count = 0;
                for (var i = 0; i < data.result.length; i++) {
                    var countTemporary = data.result[i].value;
                    if (i != 0) {
                        data.result[i].value = parseInt((count - parseInt(data.result[i].value)) / 1024) + "KB  ";
                        
                    }
                    count = countTemporary;
                    
                }
                netdatas.push(data);
                console.log(data);
                
               

            }
        });
    });
    $("#" + idname).html("");
    $("#" + idname).append(name + "</br>");
    console.log("netdatas"+netdatas);
    $.each(netdatas[0].result, function (i, e) {
        var date2 = timestampToTime(parseInt(e.clock));

        if (i != 0) {
            $("#" + idname).append("时间:" + date2);
            $("#" + idname).append(" 请求流量 :" +  e.value);
        
        $.each(netdatas[1].result, function (ii, ee) {
            if (ee.clock == e.clock) {
                $("#" + idname).append(" 响应流量 :" +  ee.value);
            }
            });

        

        $.each(netdatas[2].result, function (iii, eee) {
            if (eee.clock == e.clock) {
                $("#" + idname).append(" 总流量 :" + eee.value);
            }
        });
            $("#" + idname).append(" </br>");
    }

      
    });



    
}

注意:

     1. 监控数据必须在zabbix 中创建相关监控项才可以获取到数据。

     2.网络数据是流量和,并不是此时刻的流量数。

 

 

网络数据

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QFN-齐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值