GetItems.py
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: 返回认证秘钥
'''
LoginApiData = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.User,
"password": self.Pwd
},
"id": 1
}
LoginRet = requests.post(url=self.ApiUrl, data=json.dumps(LoginApiData), headers=self.__Headers)
if LoginRet.status_code is not 200:
return 1001
else:
try:
LoginRet = LoginRet.json()
except:
return 1001
if 'result' in LoginRet:
Result = LoginRet['result']
return Result
else:
return 1002
def __GetMonitorHost(self):
Auth = self.__Login()
if Auth == 1001:
return 1001
elif Auth == 1002:
return 1002
else:
HostApiData = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["hostid", "host", "name"],
"selectInterfaces": ["interfaces", "ip"],
},
"auth": Auth,
"id": 1
}
HostRet = requests.post(url=self.ApiUrl, data=json.dumps(HostApiData), headers=self.__Headers).json()
if 'result' in HostRet:
if len(HostRet['result']) != 0:
Allhost = {}
for host in HostRet['result']:
HostInfo = {'host': host['host'], 'hostid': host['hostid'], 'ip': host['interfaces'][0]['ip'],
'name': host['name']}
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()
if type(HostRet) is dict:
Auth, AllHost = HostRet['Auth'], HostRet['Allhost']
NewAllHost = {}
for k in AllHost:
ItemData = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["extend", "name", "key_", "lastvalue"],
"hostids": str(k),
"search": {
"key_":
[
"system.hostname",
"system.uptime",
"io.usedgen[*]",
"disk_capacity.[disk_all_Usage]",
"system.cpu.util",
"system.cpu.num",
"system.cpu.load",
"system.cpu.util[,idle]",
"vm.memory.utilization",
"vm.memory.size[total]",
"vm.memory.size[available]",
"net.if.in",
"net.if.out"
]
},
"searchByAny": "true",
"sortfield": "name"
},
"auth": Auth,
"id": 1
}
Ret = requests.post(url=self.ApiUrl, data=json.dumps(ItemData), headers=self.__Headers).json()
if 'result' in Ret:
if len(Ret['result']) != 0:
HostInfo = AllHost[k]
for host in Ret['result']:
DiskUtilization = re.findall(r'根目录使用率监控', str(host.values()))
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():
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():
HostInfo[host['name']] = host['lastvalue']
elif 'Load average (5m avg)' in host.values():
HostInfo[host['name']] = host['lastvalue']
elif 'Load average (15m avg)' in host.values():
HostInfo[host['name']] = host['lastvalue']
elif 'idle time' in host.values():
HostInfo[host['name']] = host['lastvalue']
elif 'CPU utilization' in host.values():
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']
elif '服务器硬盘总使用率' 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
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','根目录使用率/%','CPU平均负载/1min','CPU平均负载/5min','CPU平均负载/15min','CPU空闲时间','CPU使用率/%','内存使用率/%','可用内存/G','磁盘使用率/%','低负载(是/否)']
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
for host in ZabbixData.values():
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]
NewDiskItem = DiskItem.strip('Space utilization')
DiskItemValue = str(round(float(host[item]), 2)) + '%'
if DiskItems == '':
DiskItemData = str(NewDiskItem) + ' ' + str(DiskItemValue)
else:
DiskItemData = '\n' + str(NewDiskItem) + ' ' + str(DiskItemValue)
DiskItems += DiskItemData
DelItems.append(DiskItem)
for delitem in DelItems:
host.pop(delitem)
host['Disk utilization'] = DiskItems
if 'System uptime' in host:
HostItemValues = []
HostItemValues.append(host['ip'])
HostItemValues.append(host['name'])
try:
HostItemValues.append(str(round(int(host['System uptime']) / 24 / 60 / 60, 2)) + 'd')
except IndexError as e:
print("IndexError Details : " + str(e))
pass
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(float(host['根目录使用率监控']), 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['idle time']), 2))
HostItemValues.append(str(round(float(host['CPU utilization']), 2)) + '%')
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['服务器硬盘总使用率'])
if host['Number of CPUs'] == "0":
HostItemValues.append("已停用")
if float(host['Load average (15m avg)']) >= 10 or float(round(float(host['CPU utilization']), 2)) >= 20 :
HostItemValues.append("否")
else:
HostItemValues.append("是")
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)
config.ini
[zabbix]
api_url = http://10.190.5.23/api_jsonrpc.php
user = li
password = 7QrYq
[excel]
file_name = 服务器资源使用情况分析
main.py
import configparser
import os,sys
import time
from api.zabbixapi.GetItems import Zabbix
from api.zabbixapi.SaveToExcel import WriteExcel
import datetime
path = os.path.dirname(os.path.abspath(__file__))
sys.intern(path)
if __name__ == "__main__":
print("start".center(60,"*"))
print("zabbix统计机器资源使用情况".center(60))
config = configparser.ConfigParser()
config.read(os.path.join(os.getcwd(), 'config.ini'), encoding='utf-8')
zabbix = Zabbix(
zabbix_api,
zabbix_user,
zabbix_passwd
)
starttime = datetime.datetime.now()
zabbix_data = zabbix.GetItemValue()
if len(zabbix_data) == 2:
print(zabbix_data['errmsg'])
print("end".center(60, "*"))
else:
date_time = time.strftime('%Y-%m-%d_%H-%M')
file_name = os.path.join(os.getcwd(), config.get('excel', 'file_name') + date_time + '.xlsx')
WriteExcel(file_name, zabbix_data)
endtime = datetime.datetime.now()
run_time=endtime - starttime
print(f"程序运行:{run_time.seconds} s 生成文件:{file_name}")
print("end".center(60, "*"))
调用zabbix的api接口导出主机配置信息演示
zabbix官网的API接口
curl -X POST -H 'Content-Type:application/json' -k -d '
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "nana",
"password": "123"
},
"id": 1,
"auth": null
}' https://1.1.1.1/zabbix/api_jsonrpc.php
{"jsonrpc":"2.0","result":"deb180984af5d5f185ec0c92e20dfb09","id":1}
curl -X POST -H 'Content-Type:application/json' -k -d '
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 1,
"auth": "deb180984af5d5f185ec0c92e20dfb09"
}' https://1.1.1.1/zabbix/api_jsonrpc.php
{"hostid":"11988","host":"CL-CNSNL06","interfaces":[{"interfaceid":"1851","ip":"1.1.1.1"}]}],"id":1}