当前位置:网站首页>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)
边栏推荐
- Douban scoring applet Part-3
- Feign implements dynamic URL
- LeetCode 168. Detailed explanation of Excel list name
- Jerry's synchronous weather information to equipment [chapter]
- Keep an IT training diary 054- opening and closing
- Global and Chinese market of contour projectors 2022-2028: Research Report on technology, participants, trends, market size and share
- Portable two-way radio equipment - current market situation and future development trend
- SQL statement
- What are the advantages and disadvantages of data center agents?
- 1189. Maximum number of "balloons"
猜你喜欢

Override and virtual of classes in C #

Dans la recherche de l'intelligence humaine ai, Meta a misé sur l'apprentissage auto - supervisé

17. File i/o buffer

Small program graduation project based on wechat reservation small program graduation project opening report reference

Pytoch residual network RESNET

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

Remember another interview trip to Ali, which ends on three sides

Conditional statements of shell programming

Yyds dry goods inventory override and virtual of classes in C

High level application of SQL statements in MySQL database (I)
随机推荐
Global and Chinese market of handheld melanoma scanners 2022-2028: Research Report on technology, participants, trends, market size and share
Advanced learning of MySQL -- Application -- index
Remember a lazy query error
From the 18th line to the first line, the new story of the network security industry
Remember another interview trip to Ali, which ends on three sides
Small program graduation project based on wechat reservation small program graduation project opening report reference
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
All ceramic crowns - current market situation and future development trend
Pyrethroid pesticide intermediates - market status and future development trend
Advanced learning of MySQL -- Application -- storage engine
Basic editing specifications and variables of shell script
FRP intranet penetration
The reasons why QT fails to connect to the database and common solutions
When the watch system of Jerry's is abnormal, it is used to restore the system [chapter]
Jerry's update contact [article]
Portapack application development tutorial (XVII) nRF24L01 launch C
Cancer biopsy instruments and kits - market status and future development trends
Ceramic metal crowns - current market situation and future development trend
Hunan University | robust Multi-Agent Reinforcement Learning in noisy environment