1-07 589 views
一、初识api(zabbix4.4.4版本)
API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。
根据单个或分布式平台上不同软件应用程序间的数据共享性能,可以将 API 分为四种类型:
远程过程调用(RPC):通过作用在共享数据缓存器上的过程(或任务)实现程序间的通信。
标准查询语言(SQL):是标准的访问数据的查询语言,通过通用数据库实现应用程序间的数据共享。
文件传输:文件传输通过发送格式化文件实现应用程序间数据共享。
信息交付:指松耦合或紧耦合应用程序间的小型格式化信息,通过程序间的直接通信实现数据共享。
二、具体操作
zabbix是有验证账号及密码的,所以api也不例外,我们首要任务是先拿到访问许可证auth字符串,通过user.login方法实现
1.获取auth字符串
这里提供2种方式获取,1种是用curl命令(shell),另1种是通过python
shell方式:
# cat get_auth.sh curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": null }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool |jq .result
执行结果:
python方式:
#!/usr/bin/env python # -*- coding:utf-8 -*- import requests import json url = 'http://127.0.0.1/zabbix/api_jsonrpc.php' post_data = { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1 } post_header = {'Content-Type': 'application/json'} ret = requests.post(url, data=json.dumps(post_data), headers=post_header) zabbix_ret = json.loads(ret.text) if not zabbix_ret.has_key('result'): print 'login error' else: print zabbix_ret.get('result')
执行结果:
2.查看主机信息
现在,我们有一个有效的用户认证令牌,可以用来访问Zabbix中的数据。例如,让我们使用host.get
方法检索所有配置主机的ID、主机名和接口:
# cat get_api_info.sh auth=`sh get_auth.sh` curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "host.get", "params": { "output": [ "hostid", "host" ], "selectInterfaces": [ "interfaceid", "ip" ] }, "id": 2, "auth": '${auth}' }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool
执行效果:
3.查看模板信息
# cat get_api_template.py # -*- coding: UTF-8 -*- import urllib2,json,cookielib,urllib from urllib2 import Request, urlopen, URLError, HTTPError global auth_code,zabbix_url,zabbix_header zabbix_url="http://127.0.0.1/zabbix/api_jsonrpc.php" zabbix_header = {"Content-Type":"application/json"} zabbix_user = "Admin" zabbix_pass = "zabbix" auth_code = "" auth_data = json.dumps({ "jsonrpc":"2.0", "method":"user.login", "params": { "user":"Admin", "password":"zabbix" }, "id":0 }) request = urllib2.Request(zabbix_url,auth_data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) try: result = urllib2.urlopen(request) except HTTPError, e: print 'The server couldn\'t fulfill the request, Error code: ', e.code except URLError, e: print 'We failed to reach a server.Reason: ', e.reason else: response=json.loads(result.read()) #print response result.close() if 'result' in response: auth_code=response['result'] else: print response['error']['data'] def Http_access(data): request = urllib2.Request(zabbix_url,data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) result = urllib2.urlopen(request) response = json.loads(result.read()) # print result.read() # print response result.close() if len(response['result']) > 0: return response['result'] def Http_access(data): request = urllib2.Request(zabbix_url,data) for key in zabbix_header: request.add_header(key,zabbix_header[key]) result = urllib2.urlopen(request) response = json.loads(result.read()) # print result.read() #print response result.close() if len(response['result']) > 0: return response['result'] def get_template(): template_data = json.dumps({ "jsonrpc": "2.0", "method": "template.get", "params": { "output": "extend" }, "auth": auth_code, "id": 1 }) return template_data templatedata = get_template() for template in Http_access(templatedata): print ("templateId: {}, templateName: {}").format(template['templateid'],template['host'])
执行结果:
4.新增被监控机器
通过host.create
方法
# cat add_hosts.sh auth=`sh get_auth.sh` curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "host.create", "params": { "host": "jh-ycy-game01-192-168-114-4", "interfaces": [ { "type": 1, "main": 1, "useip": 1, "ip": "192.168.114.4", "dns": "", "port": "10050" } ], "groups": [ { "groupid": "15" } ], "templates": [ { "templateid": "10313" }, { "templateid": "10001" } ] }, "auth": '${auth}', "id": 1 }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool
templates链接多个模板,让添加的机器自动加上了模板。注意Host,ip,zabbix地址信息需要变更成你的。
执行结果:
补充,有时我们会给主机加上自动发现监控项的功能,这边将这个功能放到模板里,加主机的时候就可以一起加上去了!如:
首先创建一个模板,点击自动发现
创建一个自动发现规则,注意键值需要你先在配置文件中定义好,不清楚可以看上文自动发现监控项那篇
创建监控项原型:
创建触发器:
现在我们就已经建好模板:
查找这个模板的id:
下面,我们用api删除刚才加的主机,重新再添加1次
5.删除被监控主机
用host.delete方法,主要是根据hostid来删除,下面params也是对应的hostid
先查出你要删除主机的hostid
# sh get_api_info.sh | grep -A 1 jh-ycy-game01-192-168-114-4 | grep hostid |cut -d \” -f 4
然后我们写成一个脚本去删除:
# cat delete_hosts.sh host_name=$1 host_id=`sh get_api_info.sh | grep -A 1 $host_name | grep hostid |cut -d \" -f 4` auth=`sh get_auth.sh` curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "host.delete", "params": [ "'$host_id'" ], "id": 2, "auth": '$auth' }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool
执行结果:
很明显删除了,注意后面加上你要删除的主机名称做参数!
6.再添加一次,这次我们把之前加上的自动发现的模板加上
执行结果:
我们自定义的2个模板都加上去了,自动发现也有了。
7.简单的批量添加主机
按照上面的添加方式,我们写个循环就可以批量添加主机了。
先将要添加的主机信息填好在txt文件中,分别是主机名称,主机Ip,主机要加入的模板id,我这只加入2个模板!
修改了下之前的脚本,info 就是txt文件
# cat for_add_hosts.sh auth_ret=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": null }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool |jq .result` auth=$auth_ret while read line do host_name=`echo $line | awk '{print $1}'` host_ip=`echo $line | awk '{print $2}'` template1=`echo $line | awk '{print $3}'` template2=`echo $line | awk '{print $4}'` curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "host.create", "params": { "host": "'$host_name'", "interfaces": [ { "type": 1, "main": 1, "useip": 1, "ip": "'$host_ip'", "dns": "", "port": "10050" } ], "groups": [ { "groupid": "15" } ], "templates": [ { "templateid": "'$template1'" }, { "templateid": "'$template2'" } ] }, "auth": '${auth}', "id": 1 }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool done < info
执行结果:
8.开启和关闭zabbix维护模式
官方文档连接:https://www.zabbix.com/documentation/3.4/zh/manual/api/reference/maintenance
我们这边按官方的来,通过maintenance.create
创建维护,maintenance.delete
删除维护。
这里需要用到gourpid(主机群组id),所以我们需要先知道主机群的id,获取方法是hostgroup.get
主机群Id获取脚本:
#!/bin/bash ret=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": null }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool |jq .result` auth=$ret curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "hostgroup.get", "params": { "output": "extend", "filter": { "name": [ "Zabbix servers", "Linux servers" ] } }, "auth": '$auth', "id": 1 }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool
执行结果:
开启/关闭 Zabbix_servers群组的维护脚本:
#!/bin/bash auth_ret=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": null }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool |jq .result` auth=$auth_ret open(){ nowtime=`date +%s` endtime=2145888000 #下面groupids可以填写多个,我这填写了2和4两个主机群组id ret=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "maintenance.create", "params": { "name": "Auto maintenance", "active_since": '$nowtime', "active_till": '$endtime', "groupids": [ "4", "2" ], "timeperiods": [ { "timeperiod_type": 0, "start_date": '$nowtime', "period": 86700 } ] }, "auth": '$auth', "id": 1 }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool` count=`echo $ret | grep error` if [[ ! $count ]];then return 0 else return 1 fi } #params可以删除多个维护项目,我这边就一个,首先你要找的这个要删除的id值 maintenanceid=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "maintenance.get", "params": { "output": "extend", "selectGroups": "extend", "selectTimeperiods": "extend" }, "id": 1, "auth": '$auth' }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool |jq .result[0].maintenanceid` close(){ ret=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "maintenance.delete", "params": [ '$maintenanceid' ], "auth": '$auth', "id": 1 }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool` count=`echo $ret | grep error` if [[ ! $count ]];then return 0 else return 1 fi } check(){ if [ $? -eq 0 ];then echo -e "\033[32m\nZabbix maintenance $1 success. \n \033[0m" else echo -e "\033[31m\nZabbix maintenance $1 failed , please check it. \n \033[0m" fi } case $1 in open) open check open ;; close) close check close ;; *) echo "sh $0 open|close" exit 1 ;; esac
执行结果:
第二次执行为啥失败呢?原因是不允许创建同名的维护计划,关闭是因为已经删除了,再次删除肯定报错啦!
上面这种是不推荐使用的,原因很简单,加入你有多个维护计划呢?不能也是走删除-创建方法吧,我们现在使用新的方法更新方法
maintenance.update 更新维护计划方法
首先查找出你创建的maintenanceid
<pre>auth=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": null }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool |jq .result` maintenanceid=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "maintenance.get", "params": { "output": "extend", "selectGroups": "extend", "selectTimeperiods": "extend" }, "id": 1, "auth": '$auth' }' http://192.168.114.3/zabbix/api_jsonrpc.php | python -m json.tool |jq .result` echo $maintenanceid
找到之后,下面就是主菜了:
首先我们尝试用python脚本去写:
# cat update_zabbix_maintenance.py #!/usr/bin/env python # encoding: utf-8 import sys,json,requests,time zabbix_info={ 'server_url': 'http://192.168.114.3/zabbix/api_jsonrpc.php', 'header' : {"Content-Type": "application/json"}, 'username' : 'Admin', 'password' : 'zabbix', 'zabbix_server_ip':'192.168.114.3',#zabbix server端的ip 'zabbix_agent_port':'7777',#zabbix-agent port 'zabbix_groups_id':'4',#zabbix要加入的用户组id 'zabbix_templateid':[10313,10316,10268],#zabbix要加入的template的id,允许多个,目前代码里只能增加三个,三个以上,则需要到代码里修改 } def zabbix_login(func_argv_server_url,func_argv_header,func_argv_username,func_argv_password): ''' 获取zabbix的认证信息 :param func_argv_server_url: zabbix url的api :param func_argv_header: 头信息 :param func_argv_username: zabbix登录的用户名 :param func_argv_password: zabbix密码 :return: 返回认证信息 ''' # 登录zabbix并获取auth的token login = { "jsonrpc": "2.0", "method": "user.login", "params": { "user": func_argv_username, "password": func_argv_password }, "auth":None, "id": 1 } auth = requests.post(func_argv_server_url, data=json.dumps(login), headers=func_argv_header) auth_ret=json.loads(auth.text) return auth_ret def update_maintenance(func_argv_zabbix_token,func_argv_start_time,func_argv_end_time,func_argv_url,func_argv_head): ''' :param func_argv_zabbix_token:zabbix认证信息token :param func_argv_start_time: 开启的维护开始时间 :param func_argv_end_time: 维护结束时间 :return: ''' maintenance_content={ "jsonrpc": "2.0", "method": "maintenance.update", "params": { "maintenanceid": "16", #这里填写你找到的maintenanceid "active_since": func_argv_start_time, "active_till": func_argv_end_time, "tags_evaltype": 0, "groupids": [ "2", "4" ], "timeperiods": [ { "timeperiod_type": 0, "start_date": func_argv_start_time, "period": 86700 } ] }, "auth": "{}".format(func_argv_zabbix_token), "id": 1 } # print(json.dumps(maintenance_content,indent=4)) update_ret=requests.post(func_argv_url,data=json.dumps(maintenance_content),headers=func_argv_head) # print(json.dumps(update_ret,indent=4)) return update_ret def running(): if sys.argv[1] == 'open': #open 代表打开维护 start_time = int(str(time.time()).split('.')[0]) start_time = int(start_time - 360) #开始维护时间在今天的0点 end_time = int(start_time + 10800) #结束维护时间在今天的24点 elif sys.argv[1] == 'close': #close 代表关闭维护 start_time = int(str(time.time()).split('.')[0]) - 86400 #开始维护时间在现在时间 end_time = int(int(str(time.time()).split('.')[0]) + 360) #结束维护时间在现在时间的后6分钟 else: print('example: python {} open|close'.format(sys.argv[0])) exit(1) zabbix_token=zabbix_login(zabbix_info['server_url'],zabbix_info['header'],zabbix_info['username'],zabbix_info['password'])['result'] ret = update_maintenance(zabbix_token,start_time,end_time,zabbix_info['server_url'],zabbix_info['header']) # print(json.dumps(ret,indent=4)) print(ret) time.sleep(10) if __name__ == '__main__': if len(sys.argv) &gt; 1: running() else: print('example: python {} open|close'.format(sys.argv[0])) exit(1)
下面尝试用shell去写:
</pre> <pre># cat update_zabbix_maintenance.sh #!/bin/bash set -e auth=`curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": null }' http://127.0.0.1/zabbix/api_jsonrpc.php | python -m json.tool |jq .result` open(){ start_time=$(echo `date +%s` - 360 | bc) end_time=$(echo `date +%s` + 10800 | bc) curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "maintenance.update", "params": { "maintenanceid": "16", "active_since": '$start_time', "active_till": '$end_time', "tags_evaltype": 0, "groupids": [ "2", "4" ], "timeperiods": [ { "timeperiod_type": 0, "start_date": '$start_time', "period": 86700 } ] }, "auth": '$auth', "id": 1 }' http://192.168.114.3/zabbix/api_jsonrpc.php &>/dev/null } close(){ start_time=$(echo `date +%s` - 86400 | bc) end_time=$(echo `date +%s` + 360 | bc) curl -s -X POST -H 'Content-Type:application/json' -d ' { "jsonrpc": "2.0", "method": "maintenance.update", "params": { "maintenanceid": "16", "active_since": '$start_time', "active_till": '$end_time', "tags_evaltype": 0, "groupids": [ "2", "4" ], "timeperiods": [ { "timeperiod_type": 0, "start_date": '$start_time', "period": 86700 } ] }, "auth": '$auth', "id": 1 }' http://192.168.114.3/zabbix/api_jsonrpc.php &>/dev/null } case $# in 1) if [[ $1 != "open" && $1 != "close" ]];then echo "sh $$ open|close" else echo -e "开始 $1 zabbix 维护" $1 echo -e "$1 zabbix 维护 done!" fi ;; *) echo "sh $0 open|close" exit 0 esac</pre> <pre>
zabbix-api初探,未完待续~
版权属于: 抓不住的疯
原文地址: https://www.ycy114.com/index.php/2020/01/07/zabbix-api%e6%8e%a5%e5%8f%a3/
转载时必须以链接形式注明原始出处及本声明。