IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> PYTHON调用ZABBIX的API导出监控历史数据的简单实现 -> 正文阅读

[Python知识库]PYTHON调用ZABBIX的API导出监控历史数据的简单实现

#!/usr/local/bin/python
# coding:utf-8

import json
import urllib2
from urllib2 import URLError
import sys
import xlrd
import getpass
import time
import datetime
import xlsxwriter

reload(sys)
sys.setdefaultencoding('utf-8')


# History object types to return.
#
# Possible values:
# 0 - numeric float;
# 1 - character;
# 2 - log;
# 3 - numeric unsigned;
# 4 - text.
#
# Default: 3.
class ZabbixTools:
    def __init__(self):
        self.url = 'http://192.168.243.99//zabbix/api_jsonrpc.php'

        self.header = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0',
                       "Content-Type": "application/json"}

    def user_login(self):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                 "user": "Admin",
                 "password": "zabbix"

            },
            "id": 0
        })

        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print("Auth Failed, please Check your name and password:", e.code)
        else:
            response = json.loads(result.read())
            result.close()
            self.authID = response['result']
            return self.authID

    def retimes(self, times):
        timeArray = time.strptime(times, "%Y-%m-%d %H:%M:%S")
        timestamp = time.mktime(timeArray)
        return timestamp

    def reshowtime(self, cptimes):
        t1 = time.localtime(cptimes)
        showtimes = time.strftime("%Y-%m-%d %H:%M:%S", t1)
        return showtimes


    def host_getbyip(self, hostip):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": ["hostid", "name", "status", "available", "proxy_hostid"],
                "filter": {"ip": hostip}
            },
            # "auth":self.user_login(),
            "auth": self.authID,
            "id": 1,
        })

        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            if hasattr(e, 'reason'):
                print
                'We failed to reach a server.'
                print
                'Reason: ', e.reason
            elif hasattr(e, 'code'):
                print
                'The server could not fulfill the request.'
                print
                'Error code: ', e.code
        else:
            response = json.loads(result.read())
            result.close()
            # print "Number Of %s: " % hostName, len(response['result'])
            lens = len(response['result'])
            # print response["result"]
            if lens > 0:
                # return response['result'][0]['name']
                # print response['result'][0]['status']
                print
                hostip, response['result'][0]['proxy_hostid'] + " " + response['result'][0]['available'] + " " + \
                response['result'][0]['name'] + " " + response['result'][0]['hostid']
                return response['result'][0]['hostid']
            else:
                print
                "error " + hostip


    def getitemids(self, hostips, itemnames):
        hostid = self.host_getbyip(hostips)
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "item.get",
            "params": {
                "output": "extend",
                "hostids": hostid,
                "filter": {
                    # "name": itemnames,
                    "key_": itemnames
                }
                # "proxy_hostid":proxyids,
            },
            "auth": self.authID,
            "id": 1,
        })
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            if hasattr(e, 'reason'):
                print
                'We failed to reach a server.'
                print
                'Reason: ', e.reason
            elif hasattr(e, 'code'):
                print
                'The server could not fulfill the request.'
                print
                'Error code: ', e.code
        else:
            response = json.loads(result.read())
            result.close()
            # print response['result']
            print(response['result'][0]["itemid"]) + " test"
            return response['result'][0]["itemid"]


    def historyvalues(self, itemids, start, stop, types=3):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "history.get",
            "params": {
                "itemids": itemids,
                "history": types,
                "sortfield": "clock",
                "sortorder": "DESC",
                "time_from": int(start),
                "time_till": int(stop),
                "limit": 100000
            },
            "auth": self.authID,
            "id": 1,
        })
        request = urllib2.Request(self.url, data)
        for key in self.header:
            request.add_header(key, self.header[key])

        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            if hasattr(e, 'reason'):
                print
                'We failed to reach a server.'
                print
                'Reason: ', e.reason
            elif hasattr(e, 'code'):
                print
                'The server could not fulfill the request.'
                print
                'Error code: ', e.code
        else:
            response = json.loads(result.read())
            result.close()
            # print response
            # print response['result']
            # for items in response['result']:
            #     dt=int(items['clock'])
            #     dts=self.reshowtime(dt)
            #     print dts,items['value']
            return response['result']


    def printhistory(self, ips, items, start, stop, types=3):
        starttime = self.retimes(start)
        stoptime = self.retimes(stop)
        print
        starttime, stoptime
        itemid = self.getitemids(ips, items)

        results = self.historyvalues(itemid, starttime, stoptime, types)

        nowtime = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + ""
        filenames = nowtime + 'iteminfos.xlsx'
        workbook1 = xlsxwriter.Workbook(filenames)
        worksheet = workbook1.add_worksheet()
        t1 = 'ZABBIX监控数据'
        format = workbook1.add_format()
        format.set_bold()
        yellow = workbook1.add_format(
            {'align': 'center', 'valign': 'vcenter', 'font_size': 22, 'fg_color': 'FFC1C1'})
        yellow.set_bold()
        # worksheet.merge_range(0,0,0,4,t1,yellow)
        worksheet.merge_range('A1:B1', t1, yellow)
        worksheet.set_row(0, 38)
        worksheet.set_column("A:A", 30)
        worksheet.set_column("B:B", 60)
        title = [u'主机IP', u'时间', u'键值' + items]
        format = workbook1.add_format()
        # worksheet.set_column(0,15,20)
        format = workbook1.add_format({'align': 'center', 'valign': 'vcenter'})
        format.set_bold()
        worksheet.write_row('A2', title, format)
        worksheet.set_row(1, 25)
        row = 2
        for items in results:
            dt = int(items['clock'])
            dts = self.reshowtime(dt)
            # print dts,items['value']
            worksheet.write(row, 0, ips)
            worksheet.write(row, 1, dts)
            worksheet.write(row, 2, items['value'])
            row = row + 1
        workbook1.close()


    def printhistorylist(self, ips, items, start, stop, types=3):
        starttime = self.retimes(start)
        stoptime = self.retimes(stop)
        print
        starttime, stoptime
        itemid = self.getitemids(ips, items)

        results = self.historyvalues(itemid, starttime, stoptime, types)
        return results


    def printmanyitemexcel(self, ary1, items):
        nowtime = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + ""
        filenames = nowtime + 'iteminfos.xlsx'
        workbook1 = xlsxwriter.Workbook(filenames)
        worksheet = workbook1.add_worksheet()
        t1 = 'ZABBIX监控数据'
        format = workbook1.add_format()
        format.set_bold()
        yellow = workbook1.add_format(
            {'align': 'center', 'valign': 'vcenter', 'font_size': 22, 'fg_color': 'FFC1C1'})
        yellow.set_bold()
        # worksheet.merge_range(0,0,0,4,t1,yellow)
        worksheet.merge_range('A1:B1', t1, yellow)
        worksheet.set_row(0, 38)
        worksheet.set_column("A:A", 30)
        worksheet.set_column("B:B", 60)
        title = [u'主机IP', u'时间', u'键值' + items]
        format = workbook1.add_format()
        # worksheet.set_column(0,15,20)
        format = workbook1.add_format({'align': 'center', 'valign': 'vcenter'})
        format.set_bold()
        worksheet.write_row('A2', title, format)
        worksheet.set_row(1, 25)
        row = 2
        ipaddress = ''
        for items in ary1:
            if items.has_key('ipaddress'):
                ipaddress = items['ipaddress']
            else:
                dt = int(items['clock'])
                dts = self.reshowtime(dt)
                # print dts,items['value']
                worksheet.write(row, 0, ipaddress)
                worksheet.write(row, 1, dts)
                worksheet.write(row, 2, items['value'])
                row = row + 1
        workbook1.close()

    def manyhostsvalues(self, files, keys, types, starttimes, stoptimes):
        ary1 = []
        myfile = open(files, 'r')
        for line in myfile:
            con = line.split()
            ips = con[0].strip()
            arys = test.printhistorylist(ips, keys, starttimes, stoptimes, types)
            m = dict()
            m["ipaddress"] = ips
            arys.insert(0, m)
            ary1.extend(arys)
            print
            arys
        # print ary1

        self.printmanyitemexcel(ary1, keys)


if __name__ == '__main__':
    test = ZabbixTools()
    test.user_login()
    test.manyhostsvalues("1.txt", "net.if.in[ens32]", 3, "2022-2-25 0:00:00", "2022-3-2 11:00:00")

#把IP列表写在同一目录的1.txt

调用的API:?history.gethttps://www.zabbix.com/documentation/4.4/en/manual/api/reference/history/get

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-03-15 22:28:05  更:2022-03-15 22:31:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 21:03:35-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码