通过Python预测zabbix监控数据

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author : liuyu
# date : 2018/9/4 0004
import requests

import math,json,time
import matplotlib.pyplot as plt

class ZabbixApi(object):

    def __init__(self, username, password, apiurl):
        self.apiurl = apiurl
        self.username = username
        self.password = password
        self.token = ""

    def gettoken(self):
        data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": self.username,
                "password": self.password
            },
            "id": 1,
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        if errormsg:
            return errormsg
        self.token = jsonrequest.get("result", "")
        return self.token

    def getidfromgroupname(self, groupname):
        data = {
            "jsonrpc": "2.0",
            "method": "hostgroup.get",
            "params": {
                "output": "extend",
                "filter": {
                    "name": groupname,
                }
            },
            "auth": self.token,
            "id": 1
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        if errormsg:
            return errormsg
        return jsonrequest.get("result", "")[0].get("groupid", "")

    def gethostfromgid(self, groupid):
        data = {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": "extend",
                "groupids": groupid
            },
            "auth": self.token,
            "id": 1
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        hostinfos = {}
        if errormsg:
            return errormsg
        for hostinfo in jsonrequest.get("result", ""):
            hostinfos[hostinfo.get("hostid")] = hostinfo.get("host")
        return hostinfos

    def getvaluesformkey(self, itemkey, gid):
        data = {
            "jsonrpc": "2.0",
            "method": "item.get",
            "params": {
                "output": "extend",
                "groupids": gid,
                "search": {
                    "key_": itemkey
                },
                "sortfield": "name"
            },
            "auth": self.token,
            "id": 1
        }
        r = requests.post(self.apiurl, json=data, timeout=2.5)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        hostinfos = {}
        if errormsg:
            return errormsg
        for hostinfo in jsonrequest.get("result", ""):
            hostinfos[hostinfo.get("hostid")] = {"lastvalue": hostinfo.get("lastvalue"), "error": hostinfo.get("error"),
                                                 "units": hostinfo.get("units"),"itemid":hostinfo.get("itemid")}
        return hostinfos


    def gethistoryinfo(self,itemids,limit):
        data={
            "jsonrpc": "2.0",
            "method": "history.get",
            "params": {
                "output": "extend",
                "history": 3,
                "itemids": itemids,
                "sortfield": "clock",
                "sortorder": "DESC",
                "limit": limit
            },
            "auth": self.token,
            "id": 13
        }

        r = requests.post(self.apiurl, json=data, timeout=25)
        jsonrequest = r.json()
        errormsg = jsonrequest.get("error", None)
        if errormsg:
            return errormsg
        return jsonrequest.get("result")

class HuiTu(object):

    @staticmethod
    def linefit(x, y):
        N = float(len(x))
        sx, sy, sxx, syy, sxy = 0, 0, 0, 0, 0
        for i in range(0, int(N)):
            sx += x[i]
            sy += y[i]
            sxx += x[i] * x[i]
            syy += y[i] * y[i]
            sxy += x[i] * y[i]
        a = (sy * sx / N - sxy) / (sx * sx / N - sxx)
        b = (sy - a * sx) / N
        r = abs(sy * sx / N - sxy) / math.sqrt((sxx - sx * sx / N) * (syy - sy * sy / N))
        return a, b, r

    def showpic(self,result):
        xArr = []
        yArr = []
        for data in result:
            # print(data)

            xArr.append(int(data.get("clock")))
            yArr.append(int(data.get("value")))
        x = xArr
        y = yArr

        a, b, r = self.linefit(x, y)

        print("X=", x)
        print("Y=", y)
        print("拟合结果: y = %10.15f x + %10.15f , r=%10.15f" % (a, b, r))
        plt.plot(x, y, "r:", linewidth=2)
        plt.grid(True)
        # plt.title(hostname, color='#123456')
        plt.show()
        timestamp = int((102400.00 - b) / a)

        time_local = time.localtime(timestamp)
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        return timestamp

    def run(self,result,hostname):
        # deal with data
        xArr = []
        yArr = []
        for data in result:
            # print(data)

            xArr.append(int(data.get("clock")))
            yArr.append(int(data.get("value")))
        x = xArr
        y = yArr

        a, b, r = self.linefit(x, y)

        # print("X=", x)
        # print("Y=", y)
        # print("拟合结果: y = %10.15f x + %10.15f , r=%10.15f" % (a, b, r))

        timestamp = int((102400.00 - b)/a)

        time_local = time.localtime(timestamp)
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        # time_local = time.localtime(int(key))
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        print("== 预计下次维护时间: {}".format(str(dt)))
        plt.plot(x, y, "r:", linewidth=2)
        plt.grid(True)
        plt.title("{}  {}".format(hostname,str(dt)), color='#123456')
        plt.savefig(hostname+".png")
        plt.show()
        return timestamp




zabbix_obj = ZabbixApi("Admin", "ZabbiX", "http://localhost/zabbix/api_jsonrpc.php")

zabbix_obj.gettoken()
gid = zabbix_obj.getidfromgroupname("tg_hosts")
hostinfos = zabbix_obj.gethostfromgid(gid)



def showpics():
    results=zabbix_obj.gethistoryinfo("33169",48*30)
    huitu=HuiTu()
    key=huitu.showpic(results)
    time_local = time.localtime(int(key))
    print(time_local)
    dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
    print("预计下次维护时间: {}".format(str(dt)))
    # print("主机:{} == 数据库大小:{} M == 预计下次维护时间: {}".format(value[0],value[1].get("lastvalue"),str(dt)))


# showpics()
# exit()

def keyss(ks):
    key, = ks.keys()
    return int(key)

def tablesget():
    iteminfos = zabbix_obj.getvaluesformkey("table.amount", gid)
    infos = {}
    for k in iteminfos:
        infos[hostinfos.get(k)] = iteminfos[k]

    # print(infos)
    # 按照lastvalue 的大小进行排序输出
    infos = sorted(infos.items(), key=lambda d: int(d[1].get("lastvalue")), reverse=True)

    for i in infos:
       print(i)

    print(infos)


tablesget()


def getmysqldata():
    iteminfos = zabbix_obj.getvaluesformkey("mysql.data.size", gid)
    infos = {}
    for k in iteminfos:
        infos[hostinfos.get(k)] = iteminfos[k]

    # print(infos)
    # 按照lastvalue 的大小进行排序输出
    infos = sorted(infos.items(), key=lambda d: int(d[1].get("lastvalue")), reverse=True)
    reinfolists=[]
    for i in infos:
        if 'No such file or directory]' in json.dumps(i[1]):
            continue

        if int(i[1].get("lastvalue"))>1024000:
            yugaodate="0"
        else:
            itemid = i[1].get("itemid")
            results = zabbix_obj.gethistoryinfo(itemid, 48 * 30)
            huitu=HuiTu()
            yugaodate=str(huitu.run(results,i[0]))
            reinfolists.append({yugaodate:i})
        # print("{} === 预计时间:  {}".format(str(i),yugaodate))
        time.sleep(3)

    print(reinfolists)


    reinfosort=sorted(reinfolists, key=keyss)
    for i in reinfosort :
        (key, value), = i.items()
        time_local = time.localtime(int(key))
        # 转换成新的时间格式(2016-05-05 20:28:54)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        print("城市:{} == 数据库大小:{} M == 预计下次维护时间: {}".format(value[0],value[1].get("lastvalue"),str(dt)))

getmysqldata()





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Zabbix API 来调用 Zabbix 监控数据。以下是调用 Zabbix API 获取监控数据的简单示例: 1. 首先,你需要在 Zabbix 中创建一个 API 访问令牌。在 Zabbix 管理界面中,转到 "Administration" -> "API Access",创建一个令牌并将其保存。 2. 使用 Java 的 HTTP 客户端库(如 Apache HttpClient 或 OkHttp)来发送 HTTP 请求。以下是使用 Apache HttpClient 的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class ZabbixAPIExample { public static void main(String[] args) { String zabbixAPIUrl = "https://your-zabbix-server/api_jsonrpc.php"; String zabbixAPIToken = "your-api-access-token"; HttpClient httpClient = HttpClientBuilder.create().build(); try { // 构建 API 请求 HttpPost request = new HttpPost(zabbixAPIUrl); request.addHeader("Content-Type", "application/json"); // 构建请求体 String requestBody = "{" + "\"jsonrpc\": \"2.0\"," + "\"method\": \"item.get\"," + "\"params\": {" + "\"output\": \"extend\"," + "\"host\": \"your-hostname\"," + "\"search\": {" + "\"key_\": \"your-key\"" + "}" + "}," + "\"auth\": \"" + zabbixAPIToken + "\"," + "\"id\": 1" + "}"; request.setEntity(new StringEntity(requestBody)); // 发送请求并获取响应 HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity); // 处理响应 System.out.println(responseString); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例代码中,你需要替换 `your-zabbix-server`、`your-api-access-token`、`your-hostname` 和 `your-key` 为你的实际值。这个示例代码使用了 Zabbix API 的 `item.get` 方法来获取特定主机和键的监控数据。 请注意,上述示例代码仅为演示目的,你可以根据自己的需要进行相应的调整和扩展。此外,你可能需要根据你的项目配置和依赖项,添加相关的库和引用。 希望这能帮助到你!如果你有更多问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值