python简单调用zabbixd的api接口来实现基本操作&批量添加jvm接口和批量加入模板

官方api文档:

https://www.zabbix.com/documentation/3.4/zh/manual/api

第一步:实现登录

登录取?️authID

#!/usr/bin/env python
# encoding=utf8
import requests
import json

url = 'http://xxxxxzabbix.com/api_jsonrpc.php'
header = {'Content-Type': 'application/json'}
authID = user_login(admin,xxxxxxx)

def user_login(user,password):
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": user,
                "password": password
            },
            "id": 0
        })
    request = requests.post(url, data=data, headers=header)
    response = json.loads(request.content)
    authID = response['result']
    return authID

通过ip查询

def get_hostid_by_hostip(hostip):
    # authID = user_login(admin, xxxxxxxx)
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": ["hostid", "name", "status", "host"],
                # "output":"extend",
                "filter": {"ip": hostip}
                # "selectInterfaces":["interfaces", "ip"]
            },
            "auth": authID,
            "id": 1
        })
    result = requests.post(url, data=data, headers=header)
    response = json.loads(result.content)
    if (res != 0) and (len(res) != 0):
        host_id = response['result'][0]['hostid']
    else:
        # print hostip
        # print "Can not find the vserver's hostid, Pls check! %s" % hostip
        return 0
    return host_id

批量添加jvm接口

官方接口文档:https://www.zabbix.com/documentation/4.0/zh/manual/api/reference/hostinterface/create

#!/usr/bin/env python
# encoding=utf8
import requests
import json

url = 'http://xxxxxxxxzabbix.com/api_jsonrpc.php'
header = {'Content-Type': 'application/json'}
def get_hostid_by_hostip(hostip):
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": ["hostid", "name", "status", "host"],
                "filter": {"ip": hostip}
            },
            "auth": 'XXXXXXXXXXXXXXX',
            "id": 1
        })
    result = requests.post(url, data=data, headers=header)
    response = json.loads(result.content)
    # print response
    res = response['result']
    # print res
    if (res != 0) and (len(res) != 0):
        host_id = response['result'][0]['hostid']
        # print hostip
        # print response
    else:
        # print hostip
        # print "Can not find the vserver's hostid, Pls check! %s" % hostip
        return 0
    # print host_id
    return host_id

def hostinterface_get(hostip):
    hostid = get_hostid_by_hostip(hostip)
    if hostid == 0:
        print hostip + "\x1b[1;31mhost_get error please check it"
        return False
    # print hostid
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "hostinterface.get",
            "params": {
                "output": "extend",
                "hostids": hostid
            },
            "auth": "XXXXXXXXXXXXXXXXXXXX",
            "id": 1
        })
    result = requests.post(url, data, headers=header)
    print result
    response = json.loads(result.content)
    print response.get('result')
def hostinterface_create(hostip):
    # 接口类型.
    # 可能的值:
    # 1 - agent;
    # 2 - SNMP;
    # 3 - IPMI;
    # 4 - JMX.
    hostid = get_hostid_by_hostip(hostip)
    if hostid == 0:
        print hostip + "\x1b[1;31mhost_get error please check it"
        return False
    # print hostid
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "hostinterface.create",
            "params": {
                "hostid": hostid,
                "dns": "",
                "ip": hostip,
                "main": 1,
                "port": "12345",
                "type": 4,
                "useip": 1
            },
            "auth": "XXXXXXXXXXXXXXXXXXXXXX",
            "id": 1
        })
    # res = self.get_data(data)['result']
    result = requests.post(url, data, headers=header)
    response = json.loads(result.content)
    # print response
    try:
        res = response['result']
        # print res
        if res.get('interfaceids') is not None:
            print "zabbix中添加jvm接口成功: %s" % hostip
            return True
        else:
            print "zabbix中添加jvm接口失败: %s" % hostip
            return False
    except:
        print "zabbix中添加jvm接口异常,可能是已存在!%s" % hostip
        return False

if __name__ == '__main__':
    file_path = 'prd_ip'
    with open(file_path) as iplists:
        iplists = iplists.readlines()
    for line in iplists:
        hostinterface_create(line.strip())
        # hostinterface_get(line.strip())

批量主机添加模板

#!/usr/bin/env python
# encoding=utf8
import requests
import json

url = 'http://XXXXXXcom/api_jsonrpc.php'
header = {'Content-Type': 'application/json'}

def get_hostid_by_hostip(hostip):
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": ["hostid", "name", "status", "host"],
                "filter": {"ip": hostip}
            },
            "auth": 'XXXXXXXX',
            "id": 1
        })
    result = requests.post(url, data=data, headers=header)
    response = json.loads(result.content)
    # print response
    res = response['result']
    # print res
    if (res != 0) and (len(res) != 0):
        host_id = response['result'][0]['hostid']
        # print hostip
        # print response
    else:
        # print hostip
        # print "Can not find the vserver's hostid, Pls check! %s" % hostip
        return 0
    # print host_id
    return host_id

def get_template_by_template(template):
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "template.get",
            "params": {
                "output": "extend",
                "filter": {
                    "host": [
                        template
                    ]
                }
            },
            "auth": "XXXXXXXX",
            "id": 1
        })
    result = requests.post(url, data=data, headers=header)
    response = json.loads(result.content)
    print response
    res = response['result']
    print res[0].get('templateid')
def host_template_massadd(hostip):
    hostid = get_hostid_by_hostip(hostip)
    if hostid == 0:
        print hostip + "\x1b[1;31mhost_get error please check it"
        return False
    # print hostid
    data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "template.massadd",
            "params": {
                "templates": [
                    {
                        "templateid": "10897"
                    }
                ],
                "hosts": [
                    {
                        "hostid": hostid
                    }
                ]
            },
            "auth": "XXXXXXXX",
            "id": 1
        })
    # res = self.get_data(data)['result']
    result = requests.post(url, data, headers=header)
    response = json.loads(result.content)
    # print response
    try:
        res = response['result']
        # print res
        if res.get('templateids') is not None:
            print "zabbix中添加模板成功: %s" % hostip
            return True
        else:
            print "zabbix中添加模板失败: %s" % hostip
            return False
    except:
        print "zabbix中添加模板异常,可能是已存在!%s" % hostip
        return False

if __name__ == '__main__':
    # get_template_by_template('CustomTomcat')
    file_path = 'prd_ip'
    with open(file_path) as iplists:
        iplists = iplists.readlines()
    for line in iplists:
        host_template_massadd(line.strip())


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值