当前位置:网站首页>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)
边栏推荐
- A. Min Max Swap
- When tidb meets Flink: tidb efficiently enters the lake "new play" | tilaker team interview
- JVM performance tuning and practical basic theory - medium
- 12. Gettimeofday() and time()
- Applet graduation design is based on wechat course appointment registration. Applet graduation design opening report function reference
- Remember a lazy query error
- Sword finger offer 14- I. cut rope
- Global and Chinese market of box seals 2022-2028: Research Report on technology, participants, trends, market size and share
- All metal crowns - current market situation and future development trend
- Servlet simple verification code generation
猜你喜欢

Applet graduation project based on wechat selection voting applet graduation project opening report function reference

Pytoch residual network RESNET

Introduction to graphics: graphic painting (I)

Learn these super practical Google browser skills, girls casually flirt

Comment la transformation numérique du crédit d'information de la Chine passe - t - elle du ciel au bout des doigts?

String & memory function (detailed explanation)

What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended

MySQL advanced (Advanced) SQL statement (I)

Feign implements dynamic URL

Applet graduation design is based on wechat course appointment registration. Applet graduation design opening report function reference
随机推荐
Special copy UML notes
Global and Chinese market of digital impression system 2022-2028: Research Report on technology, participants, trends, market size and share
17. File i/o buffer
在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習
Jerry's update contact [article]
Global and Chinese market of handheld melanoma scanners 2022-2028: Research Report on technology, participants, trends, market size and share
Human resource management online assignment
Override and virtual of classes in C #
Yyds dry goods inventory it's not easy to say I love you | use the minimum web API to upload files
Key knowledge of embedded driver
Chinese Mitten Crab - current market situation and future development trend
Small program graduation project based on wechat video broadcast small program graduation project opening report function reference
Final consistency of MESI cache in CPU -- why does CPU need cache
Data collection and summary
Properties of binary trees (numerical aspects)
Bacteriostatic circle scanning correction template
Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
Introduction to graphics: graphic painting (I)
Conditional statements of shell programming
Advanced learning of MySQL -- Application -- storage engine