描述
1、通過
zabbix api獲取zabbix監控資料,了解服務器使用情況,進行巡檢,2、使用
Python openpyxl寫入excel表格中,備注:
只支持
zabbix 5.0版本以上,只支持
Python3.x版本具體結構如下:
| 目錄結構: |
|---|
![]() |
config.ini:用于配置zabbix api介面地址,和用戶密碼等GetItems.py:用于獲取每臺主機指定監控項的值SaveToExcel.py:用于將資料寫入到Excel表格中main.py:主程式,運行程式
?? 運行結果,excel檔案內容如下:

?? 使用方法:
1、創建一個檔案夾,將四個腳本保存在同一個檔案夾里面,
2、修改config.ini配置項
3、執行運行main.py檔案即可,python3.8 main.py
config.ini
config.ini配置說明:
api_url:zabbix api地址
user:zabbix用戶(需要有讀權限)
password:用戶密碼
file_name:保存的excel表格名稱前綴,后綴會已時間生成,如:服務器資源使用情況分析2020-12-11_12-22-12.xlsx
config.ini內容
[zabbix]
api_url = http://172.24.xx.xx/api_jsonrpc.php
user = Admin
password = xx@zaxxxx
[excel]
file_name = 服務器資源使用情況分析
GetItems.py
該腳本中的內容為一個類,用于調zabbix api介面,獲取所有監控主機(包括server端)的指定監控項的值
GetItems.py內容
#! /usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time :2020/12/6 13:13
# @Auther :yanjie.li
# @Email :[email protected]
# @File :GetItems.py
# @Desc :呼叫zabbix api介面,獲取監控資料,zabbix-版本為5.0以上
import requests
import json
import re
class Zabbix(object):
def __init__(self, ApiUrl, User, Pwd):
self.ApiUrl = ApiUrl
self.User = User
self.Pwd = Pwd
self.__Headers = {
'Content-Type': 'application/json-rpc',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
}
self.Message = {
1001: {"errcode": "1001", "errmsg": "請求路徑錯誤,請檢查API介面路徑是否正確."},
1002: {"errcode": "1002", "errmsg": "Login name or password is incorrect."},
1003: {"errcode": "1003", "errmsg": "未獲取到監控主機,請檢查server端是否監控有主機."},
1004: {"errcode": "1004", "errmsg": "未知錯誤."},
}
def __Login(self):
'''
登陸zabbix,獲取認證的秘鑰
Returns: 回傳認證秘鑰
'''
# 登陸zabbix,介面的請求資料
LoginApiData = https://www.cnblogs.com/yanjieli/p/{"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.User,
"password": self.Pwd
},
"id": 1
}
# 向登陸介面發送post請求,獲取result
LoginRet = requests.post(url=self.ApiUrl, data=https://www.cnblogs.com/yanjieli/p/json.dumps(LoginApiData), headers=self.__Headers)
# 判斷請求是否為200
if LoginRet.status_code is not 200:
return 1001
else:
# 如果是200狀態,則進行資料格式化
try:
LoginRet = LoginRet.json()
except:
return 1001
# 如果result在回傳資料中,那么表示請求成功,則獲取認證key
if'result' in LoginRet:
Result = LoginRet['result']
return Result
# 否則回傳用戶或密碼錯誤
else:
return 1002
def __GetMonitorHost(self):
# 呼叫登陸函式,獲取auth,并判斷是否登陸成功
Auth = self.__Login()
if Auth == 1001:
return 1001
elif Auth == 1002:
return 1002
else:
HostApiData = https://www.cnblogs.com/yanjieli/p/{"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["hostid", "host", "name"],
"selectInterfaces": ["interfaces", "ip"],
},
"auth": Auth,
"id": 1
}
# 向host.get介面發起請求,獲取所有監控主機
HostRet = requests.post(url=self.ApiUrl, data=https://www.cnblogs.com/yanjieli/p/json.dumps(HostApiData), headers=self.__Headers).json()
if'result' in HostRet:
if len(HostRet['result']) != 0:
# 回圈處理每一條記錄,進行結構化,最終將所有主機加入到all_host字典中
Allhost = {}
for host in HostRet['result']:
# host = {'hostid': '10331', 'host': '172.24.125.24', 'name': 'TBDS測驗版172.24.125.24', 'interfaces': [{'ip': '172.24.125.24'}]}
# 進行結構化,提取需要的資訊
HostInfo = {'host': host['host'], 'hostid': host['hostid'], 'ip': host['interfaces'][0]['ip'],
'name': host['name']}
# host_info = {'host': '172.24.125.24', 'hostid': '10331', 'ip': '172.24.125.24', 'name': 'TBDS測驗版172.24.125.24'}
# 加入到all_host中
Allhost[host['hostid']] = HostInfo
return {"Auth":Auth, "Allhost":Allhost}
else:
return 1003
else:
return 1001
def GetItemValue(self):
'''
# 呼叫item.get介面,獲取監控項(監控項中帶有每個監控項的最新監控資料) 介面說明檔案:https://www.zabbix.com/documentation/4.0/zh/manual/api/reference/item/get
Returns: 回傳所有監控主機監控資訊,
'''
# 獲取所有的主機
HostRet = self.__GetMonitorHost()
# 判斷HostRet是否有主機和認證key存在,這里如果是型別如果是欄位,那邊表示一定獲取到的有主機資訊,如果不是,則表示沒有獲取到值
if type(HostRet) is dict:
# 首先拿到認證檔案和所有主機資訊
Auth, AllHost = HostRet['Auth'], HostRet['Allhost']
# 定義一個新的allhost,存放所有主機新的資訊
NewAllHost = {}
# 回圈向每個主機發起請求,獲取監控項的值
for k in AllHost:
ItemData = https://www.cnblogs.com/yanjieli/p/{"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["extend", "name", "key_", "lastvalue"],
"hostids": str(k),
"search": {
"key_":
[
"system.hostname", # 主機名
"system.uptime", # 系統開機時長
"vfs.fs.size", # 檔案系統磁盤空間使用率
"system.cpu.util", # cpu使用率
"system.cpu.num", # cpu核數
"system.cpu.load", # cpu平均負載
"system.cpu.util[,idle]", # cpu空閑時間
"vm.memory.utilization", # 記憶體使用率
"vm.memory.size[total]", # 記憶體總大小
"vm.memory.size[available]", # 可用記憶體
"net.if.in", # 網卡每秒流入的位元(bit)數
"net.if.out" # 網卡每秒流出的位元(bit)數
]
},
"searchByAny": "true",
"sortfield": "name"
},
"auth": Auth,
"id": 1
}
# 向每一臺主機發起請求,獲取監控項
Ret = requests.post(url=self.ApiUrl, data=https://www.cnblogs.com/yanjieli/p/json.dumps(ItemData), headers=self.__Headers).json()
if'result' in Ret:
# 判斷每臺主機是否有獲取到監控項,如果不等于0表示獲取到有監控項
if len(Ret['result']) != 0:
# 從所有主機資訊中取出目前獲取資訊的這臺主機資訊存在host_info中
HostInfo = AllHost[k]
# 回圈處理每一臺主機的所有監控項
for host in Ret['result']:
# 匹配所有磁區掛載目錄使用率的正則運算式
DiskUtilization = re.findall(r'vfs\.fs\.size\[/[0-9a-z]{0,}\,pused\]', str(host.values()))
# print(DiskUtilization)
if len(DiskUtilization) == 1: #如果匹配到了磁區目錄,進行保存
HostInfo[host['name']] = host['lastvalue']
# 匹配網卡進出流量的正則運算式
NetworkBits = re.findall(r'Interface.*: Bits [a-z]{4,8}', str(host.values()))
if len(NetworkBits) == 1:
HostInfo[host['name']] = host['lastvalue']
elif 'System name' in host.values(): # 匹配主機名,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'System uptime' in host.values(): # 匹配系統開機運行時長,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Number of CPUs' in host.values(): # 匹配CPU核數,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Total memory' in host.values(): # 匹配記憶體總大小,進行保存
HostInfo[host['name']] = host['lastvalue']
elif '/: Total space' in host.values(): # 匹配根目錄總量,進行保存
HostInfo[host['name']] = host['lastvalue']
elif '/: Used space' in host.values(): # 匹配根目錄使用量,進行保存
HostInfo[host['name']] = host['lastvalue']
elif '/: Space utilization' in host.values(): # 匹配根目錄使用量,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Load average (1m avg)' in host.values(): # 匹配CPU平均1分鐘負載,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Load average (5m avg)' in host.values(): # 匹配CPU平均5分鐘負載,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Load average (15m avg)' in host.values(): # 匹配CPU平均15分鐘負載,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'CPU idle time' in host.values(): # 匹配CPU空閑時間,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'CPU utilization' in host.values(): # 匹配CPU使用率,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Memory utilization' in host.values(): # 匹配記憶體使用率,進行保存
HostInfo[host['name']] = host['lastvalue']
elif 'Available memory' in host.values(): # 匹配可用記憶體大小,進行保存
HostInfo[host['name']] = host['lastvalue']
NewAllHost[HostInfo['hostid']] = HostInfo
else:
return {"errcode": "1001", "errmess": "Login name or password is incorrect."}
return NewAllHost
elif HostRet == 1001:
return self.Message[1001]
elif HostRet == 1002:
return self.Message[1002]
elif HostRet == 1003:
return self.Message[1003]
else:
return self.Message[1004]
SaveToExcel.py
該腳本用于將從
zabbix獲取的所有資料寫入到Excel表格中
SaveToExcel.py內容
#! /usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time :2020/12/6 21:23
# @Auther :yanjie.li
# @Email :[email protected]
# @File :SaveToExcel.py
import re
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Side, Border, PatternFill
def WriteExcel(FilaPath, ZabbixData):
WorkBook = Workbook()
Sheet = WorkBook.active
Sheet.title = '服務器資源使用情況'
TableTitle = ['IP','主機名','運行時長/天','CPU/核','記憶體/GB','根目錄總量/G','根目錄使用量/G','根目錄使用率/%','CPU平均負載/1min','CPU平均負載/5min','CPU平均負載/15min','CPU空閑時間','CPU使用率/%','記憶體使用率/%','可用記憶體/G','磁盤使用率/%']
TitleColumn = {} #存放每個title值所對應的列{'IP': 'A', '主機名': 'B', '運行時長': 'C', 'CPU/核': 'D', '記憶體/GB': 'E', '根目錄總量': 'F',...}
AllHostItemValues = [] #存放所有主機的監控項值 串列資訊,
# 維護表頭,寫入表頭資料
for row in range(len(TableTitle)):
Col = row + 1
Column = Sheet.cell(row=1, column=Col) #獲取單元格的位置
Column.value = https://www.cnblogs.com/yanjieli/p/TableTitle[row] #寫入資料
TitleCol = Column.coordinate.strip('1') #獲取Title所在的列
TitleColumn[TableTitle[row]] = TitleCol #加入到TitleColumn
# 整理Zabbix 監控資料逐行寫入到表格中
for host in ZabbixData.values():
# 1.首先要對磁區目錄使用率進行一個整合,將除/目錄外的磁區目錄使用率整合為一個值
DiskItems = '' #定義一個空值,用于存放除根目錄空間使用率外所有的磁區目錄使用率
DelItems = [] #定義一個空串列,用于存放除根目錄空間使用率外所有的磁區目錄使用率的鍵值
for item in host:
DiskItem = re.findall(r'^/[a-z0-9]{1,50}: Space utilization', item)
if len(DiskItem) == 1:
DiskItem = DiskItem[0] #獲取監控項的名字 /boot: Space utilization
NewDiskItem = DiskItem.strip('Space utilization') # 將名字格式化,/boot: Space utilization 格式化為:/boot:
DiskItemValue = https://www.cnblogs.com/yanjieli/p/str(round(float(host[item]), 2)) +'%' # 取出對應監控項的值,并格式化保留兩位小數
# 將所有磁區目錄使用率組合為一個整的磁盤使用率
if DiskItems == '':
DiskItemData = https://www.cnblogs.com/yanjieli/p/str(NewDiskItem) +' ' + str(DiskItemValue)
else:
DiskItemData = 'https://www.cnblogs.com/n' + str(NewDiskItem) + ' ' + str(DiskItemValue)
DiskItems += DiskItemData
# 將處理完的磁盤使用率加入到DelItems串列中,供后續洗掉使用
DelItems.append(DiskItem)
# 2.將已經整合過的磁區目錄使用率監控項在原來的主機監控項中洗掉
for delitem in DelItems:
host.pop(delitem)
# 3.將整合好的磁區目錄使用率,重新加入到主機監控項的字典中
host['Disk utilization'] = DiskItems
# 4.將每臺主機監控項的值取出來組成一個串列
# 最終得到一條一條這樣的資料:
# ['172.24.125.12', 'tbds-172-24-125-12', '245.87d', '16', 64, '50G', 7.43, '14.87%', '0.1', '0.18', '0.32', 97.79, '2.21%', '35.52%', 40.45, '/boot: 14.23%\n/data: 6.24%\n/home: 0.03%']
HostItemValues = [] #定義一個空串列,用于存放主機的監控項的值
HostItemValues.append(host['ip'])
HostItemValues.append(host['System name'])
HostItemValues.append(str(round(int(host['System uptime']) / 24 / 60 / 60, 2)) + 'd') # 首先將運行時長換算為天數,然后再加入到串列中
HostItemValues.append(host['Number of CPUs'])
TotalMemory = int(int(host['Total memory']) / 1024 / 1024 / 1024)
if TotalMemory == 7:
TotalMemory = 8
elif TotalMemory == 15:
TotalMemory = 16
elif TotalMemory == 31:
TotalMemory = 32
elif TotalMemory == 62:
TotalMemory = 64
elif TotalMemory == 251:
TotalMemory = 256
elif TotalMemory == 503:
TotalMemory = 512
HostItemValues.append(TotalMemory) # 記憶體總大小
HostItemValues.append(str(round(int(host['/: Total space']) / 1024 / 1024 / 1024)) + 'G') # 根目錄總共大小
HostItemValues.append(str(round(int(host['/: Used space']) / 1024 / 1024 / 1024, 2)) + 'G') # 根目錄使用量
HostItemValues.append(str(round(float(host['/: Space utilization']), 2)) + '%') # 根目錄使用率
HostItemValues.append(host['Load average (1m avg)'])
HostItemValues.append(host['Load average (5m avg)'])
HostItemValues.append(host['Load average (15m avg)'])
HostItemValues.append(round(float(host['CPU idle time']), 2)) # CPU空閑時間
HostItemValues.append(str(round(float(host['CPU utilization']), 2)) + '%') # CPU使用率
HostItemValues.append(str(round(float(host['Memory utilization']), 2)) + '%') # 記憶體使用率
HostItemValues.append(str(round(int(host['Available memory']) / 1024 / 1024 / 1024, 2)) + 'G') # 可用記憶體
HostItemValues.append(host['Disk utilization']) # 磁盤使用率
# 將每一臺主機的所有監控項資訊添加到AllHostItems串列中
AllHostItemValues.append(HostItemValues)
# 將所有資訊寫入到表格中
for HostValue in range(len(AllHostItemValues)):
Sheet.append(AllHostItemValues[HostValue])
############ 設定單元格樣式 ############
# 字體樣式
TitleFont = Font(name="宋體", size=12, bold=True, italic=False, color="000000")
TableFont = Font(name="宋體", size=11, bold=False, italic=False, color="000000")
# 對齊樣式
alignment = Alignment(horizontal="center", vertical="center", text_rotation=0, wrap_text=True)
# 邊框樣式
side1 = Side(style='thin', color='000000')
border = Border(left=side1, right=side1, top=side1, bottom=side1)
# 填充樣式
pattern_fill = PatternFill(fill_type='solid', fgColor='99ccff')
# 設定列寬
column_width = {'A': 15, 'B': 30, 'C': 14, 'D': 10, 'E': 10, '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]
# 設定首行的高度
Sheet.row_dimensions[1].height = 38
# 凍結視窗
Sheet.freeze_panes = 'A2'
# 添加篩選器
Sheet.auto_filter.ref = Sheet.dimensions
# 設定單元格字體及樣式
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=FilaPath)
main.py
該腳本是用于執行的主函式腳本
main.py內容
#! /usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time :2020/12/10 16:04
# @Auther :yanjie.li
# @Email :[email protected]
# @File :main.py
import configparser
import os
import time
from GetItems import Zabbix
from SaveToExcel import WriteExcel
if __name__ == "__main__":
config = configparser.ConfigParser()
config.read(os.path.join(os.getcwd(), 'config.ini'), encoding='utf-8')
# 實體化一個zabbix物件
zabbix = Zabbix(
config.get('zabbix', 'api_url'),
config.get('zabbix', 'user'),
config.get('zabbix', 'password')
)
# 呼叫GetItemValue方法獲取每臺監控主機的監控資料
zabbix_data = https://www.cnblogs.com/yanjieli/p/zabbix.GetItemValue()
if len(zabbix_data) == 2:
print(zabbix_data['errmsg'])
else:
date_time = time.strftime('%Y-%m-%d_%H-%M-%S')
file_name = os.path.join(os.getcwd(), config.get('excel', 'file_name') + date_time + '.xlsx')
WriteExcel(file_name, zabbix_data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/233390.html
標籤:Python
上一篇:南方人過冬靠的是一身正氣?用Python分析全網取暖器資料
下一篇:Python No.15 字典

