Python Call Zabbix API to Create Hosts

文章首发站点:OpensGalaxy.com

这是一个根据zabbix api中host.create方法来批量创建host的python程序,比较基础,大家可以举一反三,zabbix api都可以使用这样的方法来调用。

参考官方文档地址:https://www.zabbix.com/documentation/3.0/manual/api

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import json
import urllib2
# Zabbix Api url
url = "http://test.zabbix.com/zabbix/api_jsonrpc.php"
# Zabbix Api 要求的 header格式
header = {"Content-Type":"application/json"}
# 定义一个登录验证函数 auth, 这个函数会返回一个authid 方便后续程序调用。
# 官方文档中样例 "auth": "038e1d7b1735c6a5436ee9eae095879e" 这个函数就会返回这个ID。
def auth():
    '''  This is a login verification functions
    '''
   data = json.dumps(
           {
              "jsonrpc": "2.0",
              "method": "user.login",
              "params": {
                 "user": "Admin",
                 "password": "Admin_test"
              },
              "id": 0
           })
# create request object
   request = urllib2.Request(url, data)
   for key in header:
      request.add_header(key, header[key])
# auth and get authid
   try:
         result = urllib2.urlopen(request)
   except URLError as e:
      print "Auth Failed, Please Check Your Name AndPassword:", e.code
   else:
      response = json.loads(result.read())
      result.close()
      authid = response['result']
   return  authid

def createhost(hosts,proxyid=0):
    # 这个函数定义了两个变量,hosts是字典类型的用于批量添加主机格式是{"备注名称":"1.1.1.1","备注名称":"2.2.2.2"}
    # proxyid 默认是0 默认又Zabbix Server监控,如果是由Zabbix Proxy监控,这里填写proxyid 即可.(可以通过proxy.get方法过的proxyid)
    ''' This is a create hosts function
    hosts {"test01":"1.1.1.1","test02":"2.2.2.2"}
    proxyid  default=0 is server monitor , proxy monitor please set proxyid
    '''
    authid = auth()
    hostlist = hosts
    # 这里使用for循环来循环 hostlist 字典中的 "备注名称"和"ip地址",实现每次循环增加一台主机。
    for name in hostlist:
        zdata = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.create",
            "params": {
                "host": hostlist[name], # host ip
                "interfaces": [
                    {
                        "type": 1,
                        "main": 1,
                        "useip": 1,
                        "ip": hostlist[name], # host ip
                        "dns": "",
                        "port": "10050"
                    }
                ],
                "proxy_hostid": proxyid,
                "name": name, # Visible name
                "groups": [
                    {
                        "groupid": "2"
                    }
                ],
                "templates": [
                    {
                        "templateid": "10001"
                    }
                ]
            },
            "auth": authid,
            "id": 1
        })
        request = urllib2.Request(url,zdata)
        for key in header:
                request.add_header(key,header[key])
        try:
            result = urllib2.urlopen(request)
        except URLError as e:
            print "Auth Failed, Please Check Your Name AndPassword:",e.code
        else:
                response = json.loads(result.read())
                result.close()
                hostid = response['result']
        hostids = []
        hostids.append(name)
        hostids.append(hostid)
        print hostids
if __name__ == '__main__':
    hostsdict = input("Please input hostsdict:\n ")
    createhost(hostsdict)

执行结果如下:

D:\untitled1\.idea>python zabbix_auth.py
Please input hostsdict:
{"z01":"10.10.10.10","z02":"10.10.10.11"}

['z01', {u'hostids': [u'10274']}]
['z02', {u'hostids': [u'10275']}]

发表评论