• 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()
    

      

  • 相关阅读:
    activeMQ功能Demo
    业务逻辑:shiro框架的功能实现
    业务逻辑: Quartz的整合应用
    思考题
    业务逻辑:七、完成系统菜单根据登录人动态展示
    业务逻辑:五、完成认证用户的动态授权功能 六、完成Shiro整合Ehcache缓存权限数据
    业务逻辑:三、完成用户数据列表显示功能 四、完成用户添加功能
    业务逻辑:完成角色列表显示功能,二、完成角色添加功能 三、完成用户数据列表显示功能
    Struts2 看1
    Spring2 看1
  • 原文地址:https://www.cnblogs.com/banxiancode/p/13807298.html
Copyright © 2020-2023  润新知