使用背景:
生产环境中每台主机磁盘数量不同,磁盘名称不同,虚拟机磁盘名称为vd[a-z],阿里云为xvd[a-z],真实服务器为sd[a-z]等,没有标准,zabbix已经为我们预留了自动发现,通过该功能能轻松实现各种磁盘或服务的自动发现
编写相关脚本
- 发现磁盘脚本:
cat /usr/local/zabbix/etc/zabbix_agentd.conf.d/disk_name.py
#!/usr/bin/env python
import re
import json
r = r"[s|v]d[a-z]$"
rstr = re.compile(r)
disk_list = []
disk_dict = {}
with open("/proc/partitions") as f:
for line in f:
if rstr.search(line):
disk_list.append({"{#DISKNAME}":line.split()[-1:][0]})
disk_dict["data"] = disk_list
print json.dumps(disk_dict)
运行结果:
{
"data": [
{
"{#DISKNAME}": "sdb"
},
{
"{#DISKNAME}": "sda"
}
]
}
- 获取磁盘io脚本
cat /usr/local/zabbix/etc/zabbix_agentd.conf.d/disk_io.py
#!/usr/bin/env python
import sys
import psutil
import re
if len(sys.argv) < 3:
sys.exit()
disk_name,disk_oper = sys.argv[1],sys.argv[2]
# sys.argv[1] = sda|sdb|...
# sys.argv[2] = read|write
def get_Diskinfo(diskName):
r = r'%s'% diskName
dstr = re.compile(r)
disk = psutil.disk_io_counters(perdisk=True)
io_dict = {}
read_dict = {}
write_dict = {}
# io_dict = {"read":{}}
for k,v in disk.items():
if dstr.match(k):
read_dict[diskName] = read_dict.get(diskName,0) + disk[k][0]
write_dict[diskName] = write_dict.get(diskName,0) + disk[k][1]
io_dict["read"] = read_dict
io_dict["write"] = write_dict
return io_dict # return {'read': {'sda': 417110}, 'write': {'sda': 173839}}
print get_Diskinfo(disk_name)[disk_oper][disk_name]
返回结果:
{
'read': {'sda': 417110},
'write': {'sda': 173839}
}
- 添加自定义key
cat /usr/local/zabbix/etc/zabbix_agentd.conf.d/disk.conf
UserParameter=io.scandisk,/usr/bin/python /usr/local/zabbix/etc/zabbix_agentd.conf.d/disk_name.py
UserParameter=io.read_count[*],/usr/bin/python /usr/local/zabbix/etc/zabbix_agentd.conf.d/disk_io.py $1 read
UserParameter=io.write_count[*],/usr/bin/python /usr/local/zabbix/etc/zabbix_agentd.conf.d/disk_io.py $1 write