• zabbix二次开发获取历史数据pandas处理后生成表格


    运行需pip install模块py-zabbix,pandas,xlwt,openpyxl

    # -*- coding:utf-8 -*-
    import sys
    from pyzabbix import ZabbixAPI
    import time,datetime
    import pandas as pd
    
    
    class GetHistory(object):
    
        def __init__(self):
            #TODO
            self.zapi = ZabbixAPI('http://0.0.0.0/zabbix', user='username', password='password')
    
        def get_hostgroups(self,group_name):
            '''
            :param group_name: 群组名称
            :return: 群组id,主机id,主机信息
            '''
            host_param = {
                "output": ['groupid','name'],
                "filter": {"name": group_name, },
                "selectHosts": ["host"]
            }
            hostgroup_result =  self.zapi.do_request('hostgroup.get',host_param)
            groupids = hostgroup_result.get('result')[0].get('groupid')
            host_data = hostgroup_result.get('result')[0].get('hosts')
            hostids =[x.get('hostid') for x in hostgroup_result.get('result')[0].get('hosts')]
            return groupids,hostids,host_data
    
        def get_item(self,groupids,hostids,item_name=[]):
            '''
            :param groupids: 群组id
            :param hostids: 主机id
            :param item_name: 监控项名称,默认[]为全部
            :return: 监控项id,监控项id信息
            '''
            host_param = {
                "output": ["itemid","hostid","name"],
                # "output": "extend",
                "groupids": groupids,
                "hostids":hostids,
                "filter": {
                    "name": item_name
                },
            }
            item_result =  self.zapi.do_request('item.get',host_param)
            itemids = [x.get('itemid') for x in item_result.get('result')]
            items_data = item_result.get('result')
            return itemids,items_data
    
        def get_history(self,time_from,time_till,itemids,items_data,host_data,host_list = [],history_state=0):
            '''
            :param time_from: 数据开始时间戳
            :param time_till: 数据结束时间戳
            :param itemids: 监控项id
            :param items_data: 监控项id数据
            :param host_data: 主机id数据
            :param host_list: zabbix对应的主机名称列表,默认为所有主机 []
            :param history_state: 历史数据类型0:数字浮点,
            :return: 主机id数据,监控项id数据,历史数据合并后的数据
            '''
            host_param = {
                "output": ["clock", "value", "itemid"],
                "history": history_state,
                "itemids": itemids,
                "time_from": time_from,
                "time_till": time_till,
            }
            history_result =  self.zapi.do_request('history.get',host_param)
            history_data = history_result.get('result')
            #根据主机id合并所有主机或者指定主机组,监控项id信息
            if not host_list:
                host_items_data = [dict(x, **y) for x in items_data for y in host_data if x.get('hostid') == y.get('hostid')]
            else:
                host_data_new =  [y for x in host_list for y in host_data if x == y.get('host')]
                host_items_data = [dict(x, **y) for x in items_data for y in host_data_new if x.get('hostid') == y.get('hostid')]
            # 根据监控项id合并数据
            history_host_items_data = [dict(x, **y) for x in history_data for y in host_items_data if x.get('itemid') == int(y.get('itemid'))]
            return history_host_items_data
    
        def toget_data(self,group_name,item_name,host_list =[]):
            today = datetime.date.today()
            # 昨天开始时间戳
            yesterday_time = int(time.mktime((today - datetime.timedelta(days=1)).timetuple()))
            # 昨天结束时间戳
            today_time = int(time.mktime(today.timetuple())) - 1
            groupids, hostids, host_data = self.get_hostgroups(group_name)
            itemids, items_data = self.get_item(groupids,hostids,item_name)
            history_host_items_data = self.get_history(yesterday_time,today_time,itemids,items_data,host_data,host_list)
            return history_host_items_data
    
    
        def main(self):
            #TODO
            group_name = 'GROUP_NAME'
            host_list = ['HostListName',]
            item_name = [
                # 'item_name1',
                'item_name2',
            ]
            history_host_items_data = self.toget_data(group_name,item_name,host_list)
            # 'itemid','clock','value', 'hostid' ,'name','host'
            df = pd.DataFrame(history_host_items_data, columns=['clock','host', 'name', 'value'])
            df['clock'] = pd.to_datetime(df['clock'],unit='s')
            df.sort_values(by="clock", inplace=True)
            df.to_excel(sys.path[0] + r'\%s.xlsx'%group_name,index=False)
            
    
    if __name__ == '__main__':
        gh = GetHistory()
        gh.main()
    

      

  • 相关阅读:
    Java乔晓松oracle的多表查询
    定义一个地址固定的变量
    J2ME的表单元素及其事件
    J2me的异常处理和多线程
    [置顶] eclipse远程部署,静态文件实时同步插件
    newlisp debugger
    启用isqlplus
    ORA27101: shared memory realm does not exist
    windows下安装node.js及less
    em启动/关闭报错解决
  • 原文地址:https://www.cnblogs.com/banxiancode/p/13807298.html
Copyright © 2020-2023  润新知