如何采用Python zabbix

 我来答
就烦条0o
2016-08-20 · 知道合伙人软件行家
就烦条0o
知道合伙人软件行家
采纳数:33315 获赞数:46493
从事多年系统运维,喜欢编写各种小程序和脚本。

向TA提问 私信TA
展开全部
一:安装zabbix api 接口,修改zabbix api 调用接口,获取数据、

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="#key;timestamp;value\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="#key;timestamp;value\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()

四,整理数据,汇报成图形,撰写技术报告
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式