cjcmay 发表于 2019-1-19 13:59:48

基于zabbix API添加监控主机


[*]  由于zabbix监控的主机虽为同一个业务,但是由于其跨机房并且网络为为16位,两个机房导致zabbix的自动添加扫描的主机数量就差不多有12w多个,严重影响其效率和性能.
[*]  使用zabbix API的基本步骤如下:

[*]  连接http://x.x.x.x/api_jsonrpc.php,(在zabbix网页文件的目录下为api_jsonrpc.php),提供用户名和密码,并标识HTTP头部"Content-Type":"application/json",HTTP方法为post.
[*]  获取SESSION
[*]  通过SESSION建立后续连接.
[*]  提交POST数据,格式为JSON,其中存放对应的API方法,获取(提交)需要的数据

[*]  添加HOST示例(用python写的示例,python>=2.6)
[*]#!/usr/bin/env python
#coding=utf-8
import json
import urllib2
import sys
from urllib2 import Request,urlopen,URLError,HTTPError
#zabbix的地址,用户名,密码
zabbix_url="http://x.x.x.x/api_jsonrpc.php"
zabbix_header={"Content-Type":"application/json"}
zabbix_user="admin"
zabbix_pass="zabbix"
auth_code=""
#用户认证信息,最终目的是需要得到一个SESSIONID
#下面是生成一个JSON格式的数据:用户名和密码
auth_data=json.dumps(
{
"jsonrpc":"2.0",
"method":"user.login",
"params":
      {
      "user":zabbix_user,
      "password":zabbix_pass
      },
"id":0
})
request = urllib2.Request(zabbix_url,auth_data)
for key in zabbix_header:
request.add_header(key,zabbix_header)
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())
result.close()
if 'result' in response:
auth_code=response['result']
else:
print response['error']['data']
#下面是API的请求,方法是host.create创建一个主机,具体API的方法可以参考官网的,上面很全
json_data={
"method":"host.create",
"params":{'groups':[{'groupid':'8'}],
            'host':'192.168.2.208',
            'proxy_hostid':'10107',#代理服务器
            'interfaces':[{'dns':'',
                           'ip':'192.168.2.208',
                           'main':1,
                           'port':'10050',
                           'type':1,
                           'useip':1
                         }],
            'templates':[{'templateid':'10429'},{'templateid':'10129'}] #用到的模板
   }
}
json_base={
"jsonrpc":"2.0",
"auth":auth_code,
"id":1
}
json_data.update(json_base)
if len(auth_code) == 0:
sys.exit(1)
if len(auth_code) != 0:
get_host_data = json.dumps(json_data)
request = urllib2.Request(zabbix_url,get_host_data)
for key in zabbix_header:
    request.add_header(key,zabbix_header)
try:
    result = urllib2.urlopen(request)
except URLError as e:
    if hasattr(e,'reason'):
      print 'We failed to reach a server'
      print 'Reason:',e.reason
    elif hasattr(e,'code'):
      print 'The server could not fulfill the request'
      print 'Error code:',e.code
else:
    response = json.loads(result.read())
    result.close()
    print response
    print "Number of hosts",len(response['result'])
  5.其实主要还是python和API的使用方法.提供一个思路,至于如何批量操作,只需要从这里扩展就行了,文章参考吴兆松的,这书还是挺不错的.嘿嘿....
  




页: [1]
查看完整版本: 基于zabbix API添加监控主机