凯德zabbix服务器监控设备基础信息导出

Posted 我的紫霞辣辣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了凯德zabbix服务器监控设备基础信息导出相关的知识,希望对你有一定的参考价值。

该脚本一共三个文件,文件名不可改变。

1. 该脚本可以在任意可以ping通凯德zabbix server的服务器上执行
2. 这三个文件必须在同一级目录下执行
3. 执行脚本需要先安装好python3
4. 使用方法:python main.py

Getitems.py

#! /usr/bin/env python
# _*_ coding: utf-8 _*_
import requests
import json
import re

class Zabbix(object):
    def __init__(self, ApiUrl, User, Pwd):
        self.ApiUrl = ApiUrl
        self.User = User
        self.Pwd = Pwd
        self.__Headers = 
            'Content-Type': 'application/json-rpc',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
        
        self.Message = 
            1001: "errcode": "1001", "errmsg": "请求路径错误,请检查API接口路径是否正确.",
            1002: "errcode": "1002", "errmsg": "Login name or password is incorrect.",
            1003: "errcode": "1003", "errmsg": "未获取到监控主机,请检查server端是否监控有主机.",
            1004: "errcode": "1004", "errmsg": "未知错误.",
        

    def __Login(self):
        '''
        登陆zabbix,获取认证的秘钥
        Returns: 返回认证秘钥

        '''
        # 登陆zabbix,接口的请求数据
        LoginApiData = 
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": 
                "user": self.User,
                "password": self.Pwd
            ,
            "id": 1
        
        # 向登陆接口发送post请求,获取result
        LoginRet = requests.post(url=self.ApiUrl, verify=False,data=json.dumps(LoginApiData), headers=self.__Headers)
        # 判断请求是否为200
        if LoginRet.status_code is not 200:
            return 1001
        else:
            # 如果是200状态,则进行数据格式化
            try:
                LoginRet = LoginRet.json()
            except:
                return 1001
            # 如果result在返回数据中,那么表示请求成功,则获取认证key
            if 'result' in LoginRet:
                Result = LoginRet['result']
                return Result
            # 否则返回用户或密码错误
            else:
                return 1002

    def __GetMonitorHost(self):
        # 调用登陆函数,获取auth,并判断是否登陆成功
        Auth = self.__Login()
        if Auth == 1001:
            return 1001
        elif Auth == 1002:
            return 1002
        else:
            HostApiData = 
                "jsonrpc": "2.0",
                "method": "host.get",
                "params": 
                    "output": ["hostid", "host", "name"],
                    "selectInterfaces": ["interfaces", "ip"],
                ,
                "auth": Auth,
                "id": 1
            
            # 向host.get接口发起请求,获取所有监控主机
            HostRet = requests.post(url=self.ApiUrl, verify=False,data=json.dumps(HostApiData), headers=self.__Headers).json()
            # print(len(HostRet['result']))
            if 'result' in HostRet:
                if len(HostRet['result']) != 0:
                    # 循环处理每一条记录,进行结构化,最终将所有主机加入到all_host字典中
                    Allhost = 
                    for host in HostRet['result']:
                        # host = 'hostid': '10331', 'host': '172.24.125.24', 'name': 'TBDS测试版172.24.125.24', 'interfaces': ['ip': '172.24.125.24']
                        # 进行结构化,提取需要的信息
                        HostInfo = 'host': host['host'], 'hostid': host['hostid'], 'ip': host['interfaces'][0]['ip'],
                                    'name': host['name']
                        # host_info = 'host': '172.24.125.24', 'hostid': '10331', 'ip': '172.24.125.24', 'name': 'TBDS测试版172.24.125.24'
                        # 加入到all_host中
                        Allhost[host['hostid']] = HostInfo
                    # print(Allhost)主机结构化列表
                    return "Auth": Auth, "Allhost": Allhost
                else:
                    return 1003
            else:
                return 1001

    def GetItemValue(self):
        '''
        # 调用item.get接口,获取监控项(监控项中带有每个监控项的最新监控数据) 接口说明文档:https://www.zabbix.com/documentation/4.0/zh/manual/api/reference/item/get
        Returns: 返回所有监控主机监控信息,
        '''
        # 获取所有的主机
        HostRet = self.__GetMonitorHost()
        # 判断HostRet是否有主机和认证key存在,这里如果是类型如果是字段,那边表示一定获取到的有主机信息,如果不是,则表示没有获取到值

        if type(HostRet) is dict:
            # 首先拿到认证文件和所有主机信息
            Auth, AllHost = HostRet['Auth'], HostRet['Allhost']
            # 定义一个新的allhost,存放所有主机新的信息
            NewAllHost = 
            j = 1
            # 循环向每个主机发起请求,获取监控项的值
            # print("####",len(AllHost))
            for k in AllHost:
                ItemData = 
                    "jsonrpc": "2.0",
                    "method": "item.get",
                    "params": 
                        "output": ["extend", "name", "key_", "lastvalue"],
                        "hostids": str(k),
                        "search": 
                            "key_":
                                [
                                    "system.hostname",  
                                    "system.uname",
                                ]
                        ,
                        "searchByAny": "true",
                        "sortfield": "name"
                    ,
                    "auth": Auth,
                    "id": 1
                
                # 向每一台主机发起请求,获取监控项
                Ret = requests.post(url=self.ApiUrl, verify=False,data=json.dumps(ItemData), headers=self.__Headers).json()
                print(Ret)
                # print("!!!!",len(Ret))     
                if 'result' in Ret:
                    # 判断每台主机是否有获取到监控项,如果不等于0表示获取到有监控项
                    if len(Ret['result']) != 0:
                        # 从所有主机信息中取出目前获取信息的这台主机信息存在host_info中
                        HostInfo = AllHost[k]
                        # 'host': 'Zabbix server', 'hostid': '10084', 'ip': '127.0.0.1', 'name': 'Zabbix server'
                        # 循环处理每一台主机的所有监控项
                        # print(HostInfo)
                        #print("11",len(Ret['result']))
                        for host in Ret['result']:
                            HostInfo[host['name']] = host['lastvalue']
                        #print(HostInfo)
                        NewAllHost[HostInfo['hostid']] = HostInfo
                        # print(NewAllHost)
                    else:
                        j += 1
                        print("no result",Ret['result'])
                else:
                    return "errcode": "1001", "errmess": "Login name or password is incorrect."
            print(j)
            return NewAllHost
            # print(NewAllHost)

        elif HostRet == 1001:
            return self.Message[1001]
        elif HostRet == 1002:
            return self.Message[1002]
        elif HostRet == 1003:
            return self.Message[1003]
        else:
            return self.Message[1004]

SaveToExcel.py

#! /usr/bin/env python
# _*_ coding: utf-8 _*_

import re
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Side, Border, PatternFill

def WriteExcel(FilaPath, ZabbixData):
    WorkBook = Workbook()
    Sheet = WorkBook.active
    Sheet.title = '服务器资源使用情况'
    TableTitle = ['IP', '主机名','OS详情']
    TitleColumn =   
    AllHostItemValues = []  

    # 维护表头,写入表头数据
    for row in range(len(TableTitle)):
        Col = row + 1
        Column = Sheet.cell(row=1, column=Col)  # 获取单元格的位置
        Column.value = TableTitle[row]  # 写入数据
        TitleCol = Column.coordinate.strip('1')  # 获取Title所在的列
        TitleColumn[TableTitle[row]] = TitleCol  # 加入到TitleColumn

    # 整理Zabbix 监控数据逐行写入到表格中
    # print(ZabbixData)
    i = 1
    for host in ZabbixData.values():
        #print("===",host)
        HostItemValues = []  # 定义一个空列表,用于存放主机的监控项的值
        HostItemValues.append(host['ip'])
        HostItemValues.append(host['name'])
        try:
            if host["System information"] == "":
            HostItemValues.append(host['System information'])
        except KeyError as e:
            i += 1
            print(i,e)
            HostItemValues.append("Not found the System Desc")

        AllHostItemValues.append(HostItemValues)
        
    for HostValue in range(len(AllHostItemValues)):
        Sheet.append(AllHostItemValues[HostValue])
        # print(HostValue)
    ############ 设置单元格样式 ############
    # 字体样式
    TitleFont = Font(name="宋体", size=12, bold=True, italic=False, color="000000")
    TableFont = Font(name="宋体", size=11, bold=False, italic=False, color="000000")
    # 对齐样式
    alignment = Alignment(horizontal="center", vertical="center", text_rotation=0, wrap_text=True)
    # 边框样式
    side1 = Side(style='thin', color='000000')
    border = Border(left=side1, right=side1, top=side1, bottom=side1)
    # 填充样式
    pattern_fill = PatternFill(fill_type='solid', fgColor='99ccff')
    # 设置列宽
    column_width = 'A': 15, 'B': 30, 'C': 14, 'D': 10, 'E': 10, 'F': 16, 'G': 18, 'H': 18, 'I': 22, 'J': 22, 'K': 23,
                    'L': 15, 'M': 16, 'N': 16, 'O': 14, 'P': 16
    for i in column_width:
        Sheet.column_dimensions[i].width = column_width[i]
    # 设置首行的高度
    Sheet.row_dimensions[1].height = 38
    # 冻结窗口
    Sheet.freeze_panes = 'A2'
    # 添加筛选器
    Sheet.auto_filter.ref = Sheet.dimensions

    # 设置单元格字体及样式
    for row in Sheet.rows:
        for cell in row:
            if cell.coordinate.endswith('1') and len(cell.coordinate) == 2:
                cell.alignment = alignment  # 设置对齐样式
                cell.font = TitleFont  # 设置字体
                cell.border = border  # 设置边框样式
                cell.fill = pattern_fill  # 设置填充样式
            else:
                cell.font = TableFont
                cell.alignment = alignment
                cell.border = border
    WorkBook.save(filename=FilaPath)

main.py

#! /usr/bin/env python
# _*_ coding: utf-8 _*_

import configparser
import os, sys
import time
from Getitems import Zabbix
from SaveToExcel import WriteExcel
import datetime

path = os.path.dirname(os.path.abspath(__file__))
sys.intern(path)
api_url = "https://10.164.5.67/zabbix/api_jsonrpc.php"
user = "username"
password = "password"

if __name__ == "__main__":
    print("start".center(60, "*"))
    print("zabbix统计机器资源使用情况".center(60))
    # 实例化一个zabbix对象
    zabbix = Zabbix(
        api_url,
        user,
        password
    )
    starttime = datetime.datetime.now()
    # 调用GetItemValue方法获取每台监控主机的监控数据
    zabbix_data = zabbix.GetItemValue()
    print("---->",len(zabbix_data))
    if len(zabbix_data) == 2:
        print(zabbix_data['errmsg'])
        print("end".center(60, "*"))
    else:
        date_time = time.strftime('%Y-%m-%d_%H-%M')
        # print(zabbix_data)
        file_name = os.path.join(os.getcwd(), "凯德zabbix服务器数据" + date_time + '.xlsx')
        WriteExcel(file_name, zabbix_data)
        endtime = datetime.datetime.now()
        run_time = endtime - starttime
        print(f"程序运行:run_time.seconds s  生成文件:file_name")
        print("end".center(60, "*"))
CSDN 社区图书馆,开张营业! 深读计划,写书评领图书福利~

以上是关于凯德zabbix服务器监控设备基础信息导出的主要内容,如果未能解决你的问题,请参考以下文章

利用ZABBIX进行服务器自动巡检并导出报表

Zabbix监控之迁移zabbix server

ZbxTable Go语言开发的开源Zabbix报告系统

zabbix监控之迁移zabbix监控

zabbix监控搭建步骤

在本机上安装zabbix,来监控服务器 五