您的位置:首页 > 其它

调用zabbix api统计统计某个item的所有机器的history数据

2016-09-29 00:00 363 查看
这个脚本调用zabbix的api去抓取所有有$itemkey(数字类型的有效)的机器的item的指定时间的history的数据,计算出最大,最小和平均值,保存为csv文件,脚本一共输出5列(主机名,itemid,最大值,最小值,平均值)

#!/bin/bash

apiurl="http://10.1.x.x/zabbix/api_jsonrpc.php"
starttime="2016-09-01 00:00:00"
stoptime="2016-09-25 00:00:00"
username="username"
password="password"
itemkey="system.cpu.load[percpu,avg1]"
csvfile=/tmp/cpuinfo.csv

startts=`date +%s -d "$starttime"`
stopts=`date +%s -d "$stoptime"`

echo '"hostname","itemid","min","max","avg"' > $csvfile

gettoken() {
curl -d "{\"jsonrpc\": \"2.0\",\"method\": \"user.login\",\"params\": {\"user\": \"$username\",\"password\": \"$password\"},\"id\":1,\"auth\":null}" -H "Content-Type:application/json" $apiurl  2>/dev/null|sed 's/.*result":"//'|sed 's/".*$//'|| return 1
}

getdatabyitemid() {
itemdata=`curl -d "{\"jsonrpc\": \"2.0\",\"method\": \"history.get\",\"params\": {\"output\": \"extend\",\"history\": 0,\"itemids\": \"$1\",\"time_from\": $startts,\"time_till\": $stopts},\"id\": 1,\"auth\":\"$token\"}" -H "Content-Type:application/json" $apiurl  2>/dev/null`
max=`echo $itemdata|jq .|grep '      "value":'|sed 's/.*": "//'|sed 's/",//'|sort -n|tail -1`
min=`echo $itemdata|jq .|grep '      "value":'|sed 's/.*": "//'|sed 's/",//'|sort -n|head -1`
lc=`echo $itemdata|jq .|grep '      "value":'|sed 's/.*": "//'|sed 's/",//'|wc -l`
count=`echo $itemdata |jq .|grep '      "value":'|sed 's/.*": "//'|sed 's/",//'|awk '{i+=$1}'END'{print i}'`
avg=`awk 'BEGIN{printf "%.2f\n", '$count'/'$lc'}'`
echo "\"$host\",\"$1\",\"$min\",\"$max\",\"$avg\""
echo "\"$1\",\"$min\",\"$max\",\"$avg\"" >> $csvfile
}

getitems() {
curl -d "{\"jsonrpc\": \"2.0\",\"method\": \"item.get\",\"params\": {\"output\": \"extend\",\"search\": {\"key_\":\"$itemkey\"}},\"id\": 1,\"auth\":\"$token\"}" -H "Content-Type:application/json" $apiurl  2>/dev/null
}

gethostbyitemids() {
host=`curl -d "{\"jsonrpc\": \"2.0\",\"method\": \"host.get\",\"params\": {\"output\": \"extend\",\"itemids\": \"$1\"},\"id\": 1,\"auth\":\"$token\"}" -H "Content-Type:application/json" $apiurl  2>/dev/null |jq .|grep '      "host":'|awk -F'"' '{print $4}'`
echo "search host \"$host\" item \"$itemkey\" data....."
echo -n "\"$host\"," >> $csvfile
}

token=`gettoken`|| (echo "get token failed" && exit 1)
echo $token
itemids=`getitems`&& echo $itemids|jq .|grep '      "itemid":'|sed 's/.*itemid": "//'|sed 's/",//'|while read n;do gethostbyitemids $n;getdatabyitemid $n;done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: