http://qicheng0211.blog.51cto.com/3958621/1622152
下面是创建screen的脚本,可以把一个主机的所有graphs放在一个screen里查看。
#!/usr/bin/env python import urllib2 import json import argparse def authenticate(url, username, password): values = {'jsonrpc': '2.0', 'method': 'user.login', 'params': { 'user': username, 'password': password }, 'id': '0' } data = json.dumps(values) req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'}) response = urllib2.urlopen(req, data) output = json.loads(response.read()) try: message = output['result'] except: message = output['error']['data'] print message quit() return output['result'] def getGraph(hostname, url, auth, graphtype, dynamic, columns): if (graphtype == 0): selecttype = ['graphid'] select = 'selectGraphs' if (graphtype == 1): selecttype = ['itemid', 'value_type'] select = 'selectItems' values = {'jsonrpc': '2.0', 'method': 'host.get', 'params': { select: selecttype, 'output': ['hostid', 'host'], 'searchByAny': 1, 'filter': { 'host': hostname } }, 'auth': auth, 'id': '2' } data = json.dumps(values) req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'}) response = urllib2.urlopen(req, data) host_get = response.read() output = json.loads(host_get) # print json.dumps(output) graphs = [] if (graphtype == 0): for i in output['result'][0]['graphs']: graphs.append(i['graphid']) if (graphtype == 1): for i in output['result'][0]['items']: if int(i['value_type']) in (0, 3): graphs.append(i['itemid']) graph_list = [] x = 0 y = 0 for graph in graphs: graph_list.append({ "resourcetype": graphtype, "resourceid": graph, "width": "500", "height": "100", "x": str(x), "y": str(y), "colspan": "0", "rowspan": "0", "elements": "0", "valign": "0", "halign": "0", "style": "0", "url": "", "dynamic": str(dynamic) }) x += 1 if x == columns: x = 0 y += 1 return graph_list def screenCreate(url, auth, screen_name, graphids, columns): # print graphids if len(graphids) % columns == 0: vsize = len(graphids) / columns else: vsize = (len(graphids) / columns) + 1 values = {"jsonrpc": "2.0", "method": "screen.create", "params": [{ "name": screen_name, "hsize": columns, "vsize": vsize, "screenitems": [] }], "auth": auth, "id": 2 } for i in graphids: values['params'][0]['screenitems'].append(i) data = json.dumps(values) req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'}) response = urllib2.urlopen(req, data) host_get = response.read() output = json.loads(host_get) try: message = output['result'] except: message = output['error']['data'] print json.dumps(message) def main(): # 修改下面三行 url = 'http://<zabbix url>/zabbix/api_jsonrpc.php' username = "Your API Users Username" password = "Your API Users Username" parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.') parser.add_argument('hostname', metavar='H', type=str, help='Zabbix Host to create screen from') parser.add_argument('screenname', metavar='N', type=str, help='Screen name in Zabbix. Put quotes around it if you want spaces in the name.') parser.add_argument('-c', dest='columns', type=int, default=3, help='number of columns in the screen (default: 3)') parser.add_argument('-d', dest='dynamic', action='store_true', help='enable for dynamic screen items (default: disabled)') parser.add_argument('-t', dest='screentype', action='store_true', help='set to 1 if you want item simple graphs created (default: 0, regular graphs)') args = parser.parse_args() hostname = args.hostname screen_name = args.screenname columns = args.columns dynamic = (1 if args.dynamic else 0) screentype = (1 if args.screentype else 0) auth = authenticate(url, username, password) graphids = getGraph(hostname, url, auth, screentype, dynamic, columns) print "Screen Name: " + screen_name print "Total Number of Graphs: " + str(len(graphids)) screenCreate(url, auth, screen_name, graphids, columns) if __name__ == '__main__': main()
脚本使用方法:
[root@monitor sbin]# ./screen.py -h Traceback (most recent call last): File "./screen.py", line 4, in <module> import argparse ImportError: No module named argparse
解决方法:安装suricatasc
[root@localhost ~]# rpm -qa python python-2.6.6-36.el6.x86_64 [root@localhost ~]# suricatasc Traceback (most recent call last): File "/usr/bin/suricatasc", line 18, in <module> import argparse ImportError: No module named argparse # tar -xf argparse-1.3.0.tar.gz # cd argparse-1.3.0 # python setup.py install Traceback (most recent call last): File "setup.py", line 3, in <module> from setuptools import setup, find_packages ImportError: No module named setuptools 没有setuptools的模块,说明python缺少这个模块,那我们只要安装这个模块即可解决此问题,下面我们来安装一下: # tar -xf setuptools-15.2.tar.gz # cd setuptools-15.2 # python setup.py build # python setup,py install 在重新安装 # cd argparse-1.3.0 # python setup.py install
这里的第一个zabbix server就是你的主机名或者主机IP地址 第二个zabbix server就是图像名称
效果图:
通过bash脚本分析zabbix数据库,实现服务器每日故障统计
boss要求每天晚上九点发送一条短信,至各部门总监的手机上,总结一天中所有服务器的错误统计,接到任务后,我分析了一下,通过zabbix的自带功能不太好实现,于是打算通过编写shell脚本来实现,
脚本简要说明:
通过sql语句,查询出events表中一天的所有警报,通过triggers表将警报分类,然后按分类放入相应的数组,最后通过公司的短信接口,发出统计短信。
---------------------------------------------------------------------------------------------------------------------------------------------- #!/bin/sh ### ## 版本:V0.2 2010-10-21 22:28 David.zhu #------------------------------ ## array1 普通信息 ## array2 警告信息 ## array3 一般问题 ## array4 严重问题 ## array5 灾难 #----------------------------- now=`date +%s` fix=`expr $now - 86400` myconn="mysql -h 192.168.0.10 -uzabbix -pzabbix zabbix" result=`${myconn} -e "SELECT objectid FROM events WHERE value=1 AND objectid >10000 AND clock>=${fix} AND clock<=${now} ORDER BY clock DESC LIMIT 100" | grep -v "objectid"` i=0 for trid in ${result};do PRO=`${myconn} -e "SELECT priority FROM triggers t WHERE ((t.triggerid BETWEEN 000000000000000 AND 099999999999999)) AND (t.triggerid IN(${trid}))"| grep -v priority` case $PRO in 1) array1[$i]=${PRO};; 2) array2[$i]=${PRO};; 3) array3[$i]=${PRO};; 4) array4[$i]=${PRO};; 5) array5[$i]=${PRO};; *) error[$i]=${PRO};; esac i=`expr $i + 1` done message="服务器监控总结---灾难问题:${#array5[@]}个|严重问题:${#array4[@]}个|一般问题:${#array3[@]}个|警告信息:${#array2[@]}个|普通信息:${#array1[@]}个" mobile=('138*****' '138*****' '138*****' '138*****') for ((j=0;j<${#mobile[@]};j++));do number=${mobile[${j}]} /usr/local/zabbix/bin/sendsms_pro.php ${number} notitle ${message} | 2>&1 done -----------------------------------------------------------------------------------------------------------------------------------------------
注:本脚本在zabbix 1.8.3版本上测试通过,其它版本未做过测试,sendsms_pro.php为我司的短信接口,如没有接口,可以使用linux fetion来实现。