当前位置:网站首页>ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel
ZABBIX API pulls the values of all hosts of a monitoring item and saves them in Excel
2022-07-04 02:12:00 【Xiaobo】
example : Pull key value is "LinuxMemUsedPct" The value of all hosts of the monitoring item , Save to excel In file ,excel The file naming format is "LastValue(item_key).xlsx".
Py Where the script needs to be modified :
1. The initialization information is modified according to the personal environment
2. At the bottom of the script, you need to define "item_key" Variable parameters of the key value of the monitoring item
import json
import requests
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Side, Border, PatternFill
import os
import logging
class ZabbixApi:
def __init__(self): # Initialization information
self.url = 'http://10.0.xx.xx/api_jsonrpc.php'
self.user = 'xxx'
self.passwd = 'xxx'
self.header = {
'Content-Type': 'application/json-rpc',
'User-Agent': 'python/pyzabbix',
'Cache-Control': 'no-cache'
}
def UserLogin(self): # api Login operation
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.passwd
},
"id": 0,
}
return self.UrlRequest(data)
def UrlRequest(self, data): ##
request = requests.post(url=self.url,data=json.dumps(data),headers=self.header,verify=False)
response = json.loads(request.text)
return response['result']
def GetItem(self,key): # 'key_' To check lastvalue The key value of the monitoring item , By the first parameter key Pass on
data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["name","lastvalue"],
"search": {
"key_": key
},
"selectHosts": ["host"]
},
"auth": token,
"id": 1
}
return self.UrlRequest(data)
def writeExcel(self, fileName, ZabbixData):
WorkBook = Workbook()
Sheet = WorkBook.active
Sheet.title = 'ItemInfo'
TableTitle = ['host_name', "item_name","LastValue"]
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')
# TitleColumn[TableTitle[row]] = TitleCol
# Arrangement Zabbix The monitoring data is written into the table row by row
for iteminfo in ZabbixData.values():
HostItemValues = []
HostItemValues.append(iteminfo['hosts'][0]['host']) # Host name
HostItemValues.append(iteminfo['name']) # Monitoring item name
HostItemValues.append(iteminfo['lastvalue']) #LastValue
AllHostItemValues.append(HostItemValues)
# Write all information to the table
for HostValue in range(len(AllHostItemValues)):
Sheet.append(AllHostItemValues[HostValue])
print(AllHostItemValues[HostValue])
############ Set cell style ############
# Font style
TitleFont = Font(name=" Song style ", size=12, bold=True, italic=False, color="000000")
TableFont = Font(name=" Song style ", size=11, bold=False, italic=False, color="000000")
# Alignment style
alignment = Alignment(horizontal="center", vertical="center", text_rotation=0, wrap_text=True)
# Border style
side1 = Side(style='thin', color='000000')
border = Border(left=side1, right=side1, top=side1, bottom=side1)
# Fill the style
pattern_fill = PatternFill(fill_type='solid', fgColor='99ccff')
# Set column width
column_width = {'A': 25, 'B': 25, 'C': 25, 'D': 25, 'E': 25, '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]
# Set the height of the first row
Sheet.row_dimensions[1].height = 38
# Freeze window
Sheet.freeze_panes = 'A2'
# Add filter
Sheet.auto_filter.ref = Sheet.dimensions
# Set cell font and style
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=fileName)
if __name__ == '__main__':
zapi = ZabbixApi()
token = zapi.UserLogin()
print(f' Identity token is "{token}"')
item_key = 'LinuxMemUsedPct' ### Define parameters for key values of monitoring items
zabbixDict = {}
zabbixData = zapi.GetItem(item_key)
fileName = os.path.join(os.getcwd(),"LastValue" + f'({item_key})' + '.xlsx')
for host in zabbixData:
hostid = host['hosts'][0]['hostid']
zabbixDict[hostid] = host
zapi.writeExcel(fileName, zabbixDict)
边栏推荐
- Push technology practice | master these two tuning skills to speed up tidb performance a thousand times!
- Containerization technology stack
- Remember a lazy query error
- Chapter 3.4: starrocks data import - Flink connector and CDC second level data synchronization
- Career development direction
- Summarize the past to motivate yourself to move on
- MySQL advanced (Advanced) SQL statement (I)
- Rearrangement of tag number of cadence OrCAD components and sequence number of schematic page
- [software implementation series] software implementation interview questions with SQL joint query diagram
- Dans la recherche de l'intelligence humaine ai, Meta a misé sur l'apprentissage auto - supervisé
猜你喜欢
LV1 previous life archives
JVM performance tuning and practical basic theory - medium
The reasons why QT fails to connect to the database and common solutions
MySQL advanced SQL statement (1)
High level application of SQL statements in MySQL database (I)
Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
Do you know the eight signs of a team becoming agile?
Example 072 calculation of salary it is known that the base salary of an employee of a company is 500 yuan. The amount of software sold by the employee and the Commission method are as follows: Sales
Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
Chain ide -- the infrastructure of the metauniverse
随机推荐
Global and Chinese markets for electroencephalogram (EEG) devices 2022-2028: Research Report on technology, participants, trends, market size and share
Description of setting items of Jerry [chapter]
Chain ide -- the infrastructure of the metauniverse
Winter vacation daily question -- a single element in an ordered array
[typora installation package] old typera installation package, free version
All metal crowns - current market situation and future development trend
[Yugong series] February 2022 attack and defense world advanced question misc-83 (QR easy)
Format character%* s
The reasons why QT fails to connect to the database and common solutions
[leetcode daily question] a single element in an ordered array
Yyds dry goods inventory hand-in-hand teach you the development of Tiktok series video batch Downloader
17. File i/o buffer
Ceramic metal crowns - current market situation and future development trend
Yyds dry goods inventory it's not easy to say I love you | use the minimum web API to upload files
[Yugong series] February 2022 attack and defense world advanced question misc-84 (MySQL)
Chinese Mitten Crab - current market situation and future development trend
In yolov5, denselayer is used to replace focus, and the FPN structure is changed to bi FPN
LeetCode226. Flip binary tree
Data collection and summary
Summarize the past to motivate yourself to move on