当前位置:网站首页>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)
边栏推荐
- Writeup (real questions and analysis of ciscn over the years) of the preliminary competition of national college students' information security competition
- The reasons why QT fails to connect to the database and common solutions
- [typora installation package] old typera installation package, free version
- Chain ide -- the infrastructure of the metauniverse
- Career development direction
- High level application of SQL statements in MySQL database (I)
- Global and Chinese market of digital impression system 2022-2028: Research Report on technology, participants, trends, market size and share
- It's corrected. There's one missing < /script >, why doesn't the following template come out?
- Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
- Douban scoring applet Part-3
猜你喜欢

中電資訊-信貸業務數字化轉型如何從星空到指尖?

Network byte order

Three layer switching ②
![Setting function of Jerry's watch management device [chapter]](/img/0b/8fab078e1046dbc22aa3327c49faa7.jpg)
Setting function of Jerry's watch management device [chapter]

JVM performance tuning and practical basic theory - medium

Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory

Mysql-15 aggregate function

The automatic control system of pump station has powerful functions and diverse application scenarios

Life cycle of instance variables, static variables and local variables
![The contact data on Jerry's management device supports reading and updating operations [articles]](/img/89/d36e785bd94c2373c34fb95eee3a9c.jpg)
The contact data on Jerry's management device supports reading and updating operations [articles]
随机推荐
I don't know why it can't run in the project and how to change it
Summarize the past to motivate yourself to move on
mysql使用視圖報錯,EXPLAIN/SHOW can not be issued; lacking privileges for underlying table
Write the first CUDA program
Three layer switching ②
All ceramic crowns - current market situation and future development trend
Global and Chinese market of box seals 2022-2028: Research Report on technology, participants, trends, market size and share
Huawei cloud micro certification Huawei cloud computing service practice has been stable
Jerry's watch listens to the message notification of the target third-party software and pushes the message to the device [article]
LV1 tire pressure monitoring
Prose article appreciation - the rain in the warm country has never changed into cold, hard and brilliant flowers. Knowledgeable people think he is monotonous, and he thinks he is unlucky, doesn't he?
Why can't it run (unresolved)
Setting function of Jerry's watch management device [chapter]
LV1 previous life archives
Human resource management online assignment
Bacteriostatic circle scanning correction template
Will the memory of ParticleSystem be affected by maxparticles
Cancer biopsy instruments and kits - market status and future development trends
13. Time conversion function
Jerry's watch information type table [chapter]