Python Call Zabbix API to Get Hosts

文章首发站点:OpensGalaxy.com

书接上回,上一篇文章介绍了如何通过Zabbix api中的host.create方法来创建主机,并通过for循环可以实现批量创建主机。

本篇文章讲介绍如何通过host.get、hostgroup.get、hostinterface.get等方法组合起来加上一点点处理,生成上篇文章所需要的批量主机的字典格式,一气呵成的批量导出和创建主机。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import re
import urllib2
from zabbix_createhosts import *
# Zabbix Api url
url = "http://127.0.0.1:8080/zabbix/api_jsonrpc.php"
# Zabbix Api 要求的 header格式
header = {"Content-Type":"application/json"}
# 定义一个登录验证函数 auth, 这个函数会返回一个authid 方便后续程序调用。
# 官方文档中样例 "auth": "038e1d7b1735c6a5436ee9eae095879e" 这个函数就会返回这个ID。
def auth():
   data = json.dumps(
           {
              "jsonrpc": "2.0",
              "method": "user.login",
              "params": {
                 "user": "Admin",
                 "password": "zabbixAdmin"
              },
              "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
authid = auth()
# 根据组名获得组ID
def groupids(group):
    zdata = json.dumps({
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "groupids",
            "filter": {
                "name": [
                    group
                ]
            }
        },
        "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()
        groupid = response['result']
    gid = str(groupid)
    pattern = re.compile('\d')
    match = pattern.search(gid)
    if match:
       print  match.group()


# 根据组ID 获得该组下的所有host
def gethosts(gid):
    hdata = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["name", "host"],
            "filter": {
                "groupids": gid
            }
        },
        "auth": authid,
        "id": 1
    })
    request = urllib2.Request(url, hdata)
    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()
        hostlists = response['result']
        b = str(hostlists)
    match = re.sub('u','',b)
    if match is not None:
        return match

# 根据host id获得该host ip
def gethostsip(id):
    hdata = json.dumps({
    "jsonrpc": "2.0",
    "method": "hostinterface.get",
    "params": {
        "output": ["ip"],
        "hostids": id
    },
        "auth": authid,
        "id": 1
    })
    request = urllib2.Request(url, hdata)
    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()
        hostips= response['result']
        ip = str(hostips)
    a = re.search('\'ip\': u\'\d+\.\d+\.\d+\.\d+\'',ip).group()
    b = re.sub('\'ip\': u\'|\'','',str(a))
    # 删除掉 127.0.0.1
    c = re.sub('127.0.0.1','',b)
    if c is not None:
        return c

# 根据组ID 获得该组下所有host id
def gethostsid(gid):
    hdata = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["hostid"],
            "filter": {
                "groupids": gid
            }
        },
        "auth": authid,
        "id": 1
    })
    request = urllib2.Request(url, hdata)
    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()
        hostlists = response['result']
        b = str(hostlists)
        # 删除 id为10084(Zabbix Server)这台zabbix服务器本身id(如果不删除,导入到另外zabbixserver时会发生冲突)
        c = re.sub('\{u\'hostid\': u\'10084\'\}, ','',b)
    return c

# 通过gethosts函数获得组ID 2 的所有主机信息
hostslist1 = gethosts(2)
hostslist2 = re.sub('\'hostid\': \'\d+?\'\,','',hostslist1)
hostslist3 = re.sub('\{\'host\': \'Zabbix server\',  \'name\': \'Zabbix server\'\}, ','',hostslist2)
hostslist4 = re.sub('\'host\': \'.+?\',  \'name\': \'|\'|{|}|\[|\]','',hostslist3)
# 通过替换(sub)和分隔(split),得到列表类型的包换所有主机name的列表
hostslist5 = re.split(',',hostslist4)

# 空字典
e = {}
# 空list a
a = []
# 空list b
b = []

# for 循环得到包含所有主机name的list a
for i in range(len(hostslist5)):
    a.append(hostslist5[i].strip())
# for 循环得到包含所有主机IP的 list b
# 我导出的是 Linux servers 组的所有host
groupid = groupids("Linux servers")
id = gethostsid(groupid)
# 正则findall得到所有id列表,然后for循环将id值赋给gethostsip函数获得主机IP list
idlist = re.findall('\d+', id)
for key in idlist:
    b.append(gethostsip(key))
# for 循环得到包含所有主机name对应ip的字典
for i in range(len(a)):
    f = {a[i] : b[i]}
    e.update(f)  # 使用字典的更新方法for循环更新整个字典

print e

结果,得到了想要的主机和ip的映射字典。

{'test01': '192.168.0.1', 'test02': '192.168.0.2', 'test03': '192.168.0.3', ''test04': '192.168.0.4', 'test05': '192.168.0.5'}

在此程序中最开始我导入了上一篇文章中zabbix_createhosts中的所有方法“ from zabbix_createhosts import * ”,可以直接在本程序最后使用createhost(),直接创建所以导出的主机。结尾部分如下:

for i in range(len(a)):
    f = {a[i] : b[i]}
    e.update(f)  # 使用字典的更新方法for循环更新整个字典

createhost(e,10192)

这段代码有可能并不适合你的环境,其实你只要读懂了我的实现思路就可以了,作为参考,具体问题具体分析,根据实际情况做出更改,记住:“真正的财富,是一种思维方式!”

发表评论