
from zabbix_api import ZabbixAPI
import sys
import datetime
import time
import argparse
def fetch_to_csv(username,password,server,hostname,key,output,datetime1,datetime2,debuglevel):
zapi = ZabbixAPI(server=server, log_level=debuglevel)
try:
zapi.login(username, password)
except:
print "zabbix server is not reachable: %s" % (server)
sys.exit()
host = zapi.host.get({"filter":{"host":hostname}, "output":"extend"})
if(len(host)==0):
print "hostname: %s not found in zabbix server: %s, exit" % (hostname,server)
sys.exit()
else:
hostid=host[0]["hostid"]
print '*' * 100
print key
print '*' * 100
if(key==""):
print '*' * 100
items = zapi.item.get({"filter":{"hostid":hostid} , "output":"extend"})
if(len(items)==0):
print "there is no item in hostname: %s, exit" % (hostname)
sys.exit()
dict={}
for item in items:
dict[str(item['itemid'])]=item['key_']
if (output == ''):
output=hostname+".csv"
f = open(output, 'w')
str1="#keytimestampvalue\n"
if (datetime1=='' and datetime2==''):
for itemid in items:
itemidNr=itemid["itemid"]
str1=str1+itemid["key_"]+""+itemid["lastclock"]+""+itemid["lastvalue"]+"\n"
f.write(str1)
print "Only the last value from each key has been fetched, specify t1 or t1 and t2 to fetch more data"
f.close()
elif (datetime1!='' and datetime2==''):
try:
d1=datetime.datetime.strptime(datetime1,'%Y-%m-%d %H:%M:%S')
except:
print "time data %s does not match format Y-m-d H:M:S, exit" % (datetime1)
sys.exit()
timestamp1=time.mktime(d1.timetuple())
timestamp2=int(round(time.time()))
inc=0
history = zapi.history.get({"hostids":[hostid,],"time_from":timestamp1,"time_till":timestamp2, "output":"extend" })
for h in history:
str1=str1+dict[h["itemid"]]+""+h["clock"]+""+h["value"]+"\n"
inc=inc+1
f.write(str1)
f.close()
print str(inc) +" records has been fetched and saved into: " + output
elif (datetime1=='' and datetime2!=''):
for itemid in items:
itemidNr=itemid["itemid"]
str1=str1+itemid["key_"]+""+itemid["lastclock"]+""+itemid["lastvalue"]+"\n"
f.write(str1)
print "Only the last value from each key has been fetched, specify t1 or t1 and t2 to fetch more data"
f.close()
else:
try:
d1=datetime.datetime.strptime(datetime1,'%Y-%m-%d %H:%M:%S')
except:
print "time data %s does not match format Y-m-d H:M:S, exit" % (datetime1)
sys.exit()
try:
d2=datetime.datetime.strptime(datetime2,'%Y-%m-%d %H:%M:%S')
except:
print "time data %s does not match format Y-m-d H:M:S, exit" % (datetime2)
sys.exit()
timestamp1=time.mktime(d1.timetuple())
timestamp2=time.mktime(d2.timetuple())
inc=0
history =
zapi.history.get({"hostids":[hostid,],"time_from":timestamp1,"time_till":timestamp2,
"output":"extend" })
for h in history:
str1=str1+dict[h["itemid"]]+""+h["clock"]+""+h["value"]+"\n"
inc=inc+1
f.write(str1)
f.close()
print str(inc) +" records has been fetched and saved into: " + output
else:
#print "key is: %s" %(key)
itemid = zapi.item.get({"filter":{"key_":key, "hostid":hostid} , "output":"extend"})
if(len(itemid)==0):
print "item key: %s not found in hostname: %s" % (key,hostname)
sys.exit()
itemidNr=itemid[0]["itemid"]
if (output == ''):
output=hostname+".csv"
f = open(output, 'w')
str1="#keytimestampvalue\n"
if (datetime1=='' and datetime2==''):
str1=str1+key+""+itemid[0]["lastclock"]+""+itemid[0]["lastvalue"]+"\n"
#f.write(str1)
f.write(str1)
f.close()
print "Only the last value has been fetched, specify t1 or t1 and t2 to fetch more data"
elif (datetime1!='' and datetime2==''):
d1=datetime.datetime.strptime(datetime1,'%Y-%m-%d %H:%M:%S')
timestamp1=time.mktime(d1.timetuple())
timestamp2=int(round(time.time()))
history =
zapi.history.get({"history":itemid[0]["value_type"],"time_from":timestamp1,"time_till":timestamp2,
"itemids":[itemidNr,], "output":"extend" })
inc=0
for h in history:
str1 = str1 + key + "" + h["clock"] +""+h["value"] + "\n"
inc=inc+1
f.write(str1)
f.close()
print str(inc) +" records has been fetched and saved into: " + output
elif (datetime1=='' and datetime2!=''):
str1=str1+key+""+itemid[0]["lastclock"]+""+itemid[0]["lastvalue"]+"\n"
f.write(str1)
f.close()
print "Only the last value has been fetched, specify t1 or t1 and t2 to fetch more data"
else:
d1=datetime.datetime.strptime(datetime1,'%Y-%m-%d %H:%M:%S')
d2=datetime.datetime.strptime(datetime2,'%Y-%m-%d %H:%M:%S')
timestamp1=time.mktime(d1.timetuple())
timestamp2=time.mktime(d2.timetuple())
history =
zapi.history.get({"history":itemid[0]["value_type"],"time_from":timestamp1,"time_till":timestamp2,
"itemids":[itemidNr,], "output":"extend" })
inc=0
for h in history:
str1 = str1 + key + "" + h["clock"] +""+h["value"] + "\n"
inc=inc+1
print str(inc) +" records has been fetched and saved into: " + output
f.write(str1)
f.close()
二:撰写通过key获取一周内的数据
items : 在zabbix 中搜索主机,选择最新数据,找到项目(items),点击进入,能看到机器的所有keys,在负载到程序的items 字典中,程序会循环读取items ,获取数据
#/usr/bin/env python
#-*-coding:UTF-8
import os,sys,time
users=u'admin'
pawd = 'zabbix'
exc_py = '/data/zabbix/fetch_items_to_csv.py'
os.system('easy_install zabbix_api')
os.system('mkdir -p /data/zabbix/cvs/')
if not os.path.exists(exc_py):
os.system("mkdir -p /data")
os.system("wget
http://doc.bonfire-project.eu/R4.1/_static/scripts/fetch_items_to_csv.py
-O /data/zabbix/fetch_items_to_csv.py")
def work():
moniter='192.168.1.1'
ip_list =
['192.168.1.15','192.168.1.13','192.168.1.66','192.168.1.5','192.168.1.7','192.168.1.16','192.168.1.38','192.168.1.2','192.168.1.13','192.168.1.10']
for ip in ip_list:
show_items(moniter,ip )
if __name__ == "__main__":
sc = work()
三:数据采集完毕,进行格式化输出
#!/usr/bin/env python
#-*-coding:utf8-*-
import os,sys,time
workfile = '/home/zabbix/zabbix/sjz/'
def collect_info():
dict_doc = dict()
for i in os.listdir(workfile):
dict_doc[i] = list()
for v in os.listdir('%s%s' %(workfile,i)):
dict_doc[i].append(v)
count = 0
for x,y in dict_doc.items():
for p in y:
fp = '%s/%s/%s' %(workfile,x,p)
op = open(fp,'r').readlines()
np = '%s.txt' %p
os.system( """ cat %s|awk -F"" '{print $3}' >%s """ %(fp,np))
count += 1
print count
if __name__ == "__main__":
sc = collect_info()
四,整理数据,汇报成图形,撰写技术报告
步骤:
[if !supportLists]1、 [endif]在zabbix告警目录新建wxrobot.py脚本
vi /usr/local/zabbix/share/zabbix/alertscripts/wxrobot.py
粘贴以下内容:
#!/usr/bin/python
#-*- coding: utf-8 -*-
import requests
import json
import sys
import os
headers = {'Content-Type': 'application/jsoncharset=utf-8'}
api_url = "复制群聊机器人Webhook地址到这"
def msg(text):
json_text= {
"msgtype": "text",
"text": {
"content": text
},
}
print requests.post(api_url,json.dumps(json_text),headers=headers).content
if __name__ == '__main__':
text = sys.argv[1]
msg(text)
保存退出
需要安装python插件库:pip install requests
授权和更改权限:
chmod +x *.py
chown zabbix:zabbix *.py
2.Zabbix页面配置,新增告警媒介
配置动作
配置—动作—创建动作 , 事件源 选择 触发器
1、点击右上角,“ 创建动作 ”填写对应的信息;在 动作 页面填写以下信息,这里例子为以主机内存使用率超过90%为例,
计算方式:
Aand B,需要同时符合条件里面添加的条件;
条件A:主机群组等于 Linux Servers;
条件B:触发器等于linux模板的物理内存使用率持续3分钟等于90%。
2、切换到 *** 作
*** 作: 也就是在符合动作里面配置好的条件时,做出对应的动作,具体的 *** 作说明,请参考官网指导文档,填写好信息,然后点击 *** 作细节 里面的 添加
[if !supportLists]1、 [endif]恢复 *** 作配置
到这就触发器告警企业微信群机器人发送配置完成了,动作日志可以在
报表 –动作日志 页面查看
附上格式配置,参数说明和其他的格式,请参考 使用宏
*** 作发送消息内容恢复 *** 作发送消息内容
问题:{EVENT.NAME}
告警信息:{TRIGGER.NAME}
告警地址:{HOST.NAME}
监控项目:{ITEM.NAME}
监控取值:{EVENT.VALUE}
告警严重性:{EVENT.SEVERITY}
当前状态:{EVENT.STATUS}
告警时间:{EVENT.DATE} {EVENT.TIME}
事件ID:{EVENT.ID}
告警信息:{TRIGGER. NAME}
告警地址:{HOST.NAME}
监控项目:{ITEM.NAME}
监控取值:{EVENT.RECOVERY.VALUE}
告警严重性:{EVENT.SEVERITY}
当前状态:{EVENT.RECOVERY.STATUS}
告警时间:{EVENT.DATE} {EVENT.TIME}
恢复时间:{EVENT.RECOVERY.TIME}
持续时间:{EVENT.AGE}
事件ID:{EVENT.RECOVERY.ID}
技术交流欢迎加入Q群:177428068
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)