当前位置:网站首页>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)
边栏推荐
- The reasons why QT fails to connect to the database and common solutions
- Chinese Mitten Crab - current market situation and future development trend
- Magical usage of edge browser (highly recommended by program ape and student party)
- Pesticide synergist - current market situation and future development trend
- Jerry's update contact [article]
- Example 073 square sum value judgment programming requires the input of a and B, if a ²+ b ² If the result of is greater than 100, a is output ²+ b ² Value, otherwise output the result of a + B.
- LV1 previous life archives
- Software product download collection
- Experimental animal models - current market situation and future development trend
- How to subcontract uniapp and applet, detailed steps (illustration) # yyds dry goods inventory #
猜你喜欢

Chain ide -- the infrastructure of the metauniverse

On Valentine's day, I code a programmer's exclusive Bing Dwen Dwen (including the source code for free)

C learning notes: C foundation - Language & characteristics interpretation

JVM performance tuning and practical basic theory - medium

Final consistency of MESI cache in CPU -- why does CPU need cache

Save Private Ryan - map building + voltage dp+deque+ shortest circuit
![Jerry's modification setting status [chapter]](/img/23/d6eb521943b35e543a9681a98ad3be.jpg)
Jerry's modification setting status [chapter]

Basic editing specifications and variables of shell script

LeetCode226. Flip binary tree

The boss said: whoever wants to use double to define the amount of goods, just pack up and go
随机推荐
Difference between value and placeholder
LV1 tire pressure monitoring
LV1 Roche limit
Dans la recherche de l'intelligence humaine ai, Meta a misé sur l'apprentissage auto - supervisé
Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory
Mobile phone battery - current market situation and future development trend
How to view the computing power of GPU?
A fan summed up so many interview questions for you. There is always one you need!
Jerry's synchronous weather information to equipment [chapter]
Gee import SHP data - crop image
From the 18th line to the first line, the new story of the network security industry
What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended
The difference between lambda expressions and anonymous inner classes
It's corrected. There's one missing < /script >, why doesn't the following template come out?
Cancer biopsy instruments and kits - market status and future development trends
Hunan University | robust Multi-Agent Reinforcement Learning in noisy environment
Global and Chinese market for travel wheelchairs 2022-2028: Research Report on technology, participants, trends, market size and share
Conditional statements of shell programming
Learn these super practical Google browser skills, girls casually flirt
Idea if a class cannot be found, it will be red