通过Zabbix API实现对主机的增加(无主机资产的添加和带主机资产的添加)、删除、获取主机id、获取模板id、获取组id

config.yaml存储zabbix的信息(主要包括zabbix server的url 、请求头部、登陆的用户名密码)

Zabbix_Config:
  zabbix_url: http://192.168.1.179/zabbix/api_jsonrpc.php
  zabbix_header: {"Content-Type": "application/json"}
  zabbix_user: Admin
  zabbix_pass: zabbix

auth.py文件,主要是获取zabbix认证id和对zabbix的请求,包括根据主机名(host_name)或者可见名(visible_name)获取主机的id 、新增主机、新增带资产主机、主机资产变更

#/usr/bin/env python
# encoding: utf-8
import json
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
import yaml

def  Zabbix_Url_Request(zabbix_url,data,zabbix_header,*args,**kwargs):
    #print data
    # create request object
    request = urllib2.Request(zabbix_url, data, 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())
        #print  response
        return response
        result.close()


def Zabbix_Auth_Code(zabbix_url,zabbix_header,*args,**kwargs):
    with open('config.ymal') as f:
        result = yaml.load(f)
    result_zabbix_info = result['Zabbix_Config']
    zabbix_user = result_zabbix_info['zabbix_user']
    zabbix_pass = result_zabbix_info['zabbix_pass']
    # auth user and password
    # 用户认证信息的部分,最终的目的是得到一个SESSIONID
    # 这里是生成一个json格式的数据,用户名和密码
    auth_data = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params":
                {
                    "user": zabbix_user,
                    "password": zabbix_pass
                },
            "id": 0
        })
    response = Zabbix_Url_Request(zabbix_url,auth_data,zabbix_header)
    # print response
    if 'result' in response:
        #print response
        return  response['result'],response['id']

    else:
        print  response['error']['data']

host_info.py 对zabbix的主机的操作

  1 #/usr/bin/env python
  2 # encoding: utf-8
  3 import json
  4 import sys
  5 from auth import Zabbix_Auth_Code,Zabbix_Url_Request
  6 #zabbix_url = "http://192.168.1.179/zabbix/api_jsonrpc.php"
  7 #zabbix_header = {"Content-Type": "application/json"}
  8 class Host_Action(object):
  9     def __init__(self,zabbix_url,zabbix_header,host_name=None,visible_name=None,*args,**kwargs):
 10         '''
 11         实现的功能:获取主机id,增、删主机,更新zabbix主机资产表
 12         :param zabbix_url: 访问zabbix的URL
 13         :param zabbix_header:  访问头部
 14         :param host_name:  hostname
 15         :param visible_name: 可见的主机名
 16         :param args:
 17         :param kwargs:
 18         '''
 19         self.zabbix_url = zabbix_url
 20         self.zabbix_header = zabbix_header
 21         self.host_name= host_name
 22         self.visible_name = visible_name
 23     def Get_Host_Id(self):
 24         auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
 25         find_info = {}
 26         find_info['host'] = [self.host_name]
 27         find_info['name'] = [self.visible_name]
 28         for k,v in find_info.items():
 29             if v[0] == None:
 30                 find_info.pop(k)
 31         get_host_id_data = json.dumps({
 32                 "jsonrpc": "2.0",
 33                 "method": "host.get",
 34                 "params": {
 35                     "output": "extend",
 36                     "filter": find_info
 37                 },
 38                 "auth": auth_code,
 39                 "id": auth_id
 40             })
 41         host_info = Zabbix_Url_Request(zabbix_url=self.zabbix_url,data=get_host_id_data,zabbix_header=self.zabbix_header)
 42         print host_info
 43         if len(host_info['result']) != 0:
 44             hostid = host_info['result'][0]['hostid']
 45             #print hostid
 46             return hostid
 47         else:
 48             print '没有查询到主机hostids'
 49             return 0
 50     def Add_Host(self,host_ip,template_id=10001,group_id=2,type=1,main=1,userip=1,port="10050",dns="",
 51                  flag=0,host_inventory=None,*args,**kwargs):
 52         '''
 53 
 54         :param group_id: 主机关联的监控模本id(groupid)
 55         :param templateid:  主机关联的监控模板id(templateid)
 56         :param host_ip: 主机ip地址
 57         :param type:  1 - agent; 2 - SNMP; 3 - IPMI; 4 - JMX
 58         :param main: 0 - not default; 1 - default
 59         :param userip: 0 - connect using host DNS name; 1 - connect using host IP address for this host interface.
 60         :param port: Port number used by the interface
 61         :param dns:  0 - connect using host DNS name;1 - connect using host IP address for this host interface.
 62         :param flag:    是否维护主机资产,0 - 表示不录入;1 - 表示录入
 63         :param host_inventory:  主机资产表
 64         :param args:
 65         :param kwargs:
 66         :return:
 67         '''
 68         self.host_ip = host_ip
 69         self.type = type
 70         self.main = main
 71         self.userip = userip
 72         self.port = port
 73         self.flag = flag
 74         self.dns = dns
 75         self.host_inventory = host_inventory
 76         host_msg = {}
 77         if self.host_name == None:
 78             self.host_name = self.host_ip
 79         host_template_info =[{"templateid": template_id}]
 80         host_group_info = [{"groupid": group_id}]
 81         host_interfaces_info = [{
 82             "type": self.type,
 83             "main": self.main,
 84             "useip": self.userip,
 85             "ip": self.host_ip,
 86             "dns": self.dns,
 87             "port": self.port
 88         }]
 89         host_msg['host'] = self.host_name
 90         host_msg['name'] = self.visible_name
 91         host_msg['interfaces'] = host_interfaces_info
 92         host_msg['groups'] = host_group_info
 93         host_msg['templates'] = host_template_info
 94         if self.flag == 0:
 95             host_msg['inventory_mode'] = -1  # -1 - disabled; 0 - (default) manual; 1 - automatic.
 96         elif self.flag == 1:
 97             host_msg['inventory_mode'] = 0  # -1 - disabled; 0 - (default) manual; 1 - automatic.
 98         else:
 99             sys.exit(1)
100         auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
101         host_info = json.dumps({
102                 "jsonrpc": "2.0",
103                 "method": "host.create",
104                 "params": host_msg,
105                 "auth": auth_code,
106                 "id": auth_id
107             })
108         add_host = Zabbix_Url_Request(zabbix_url=self.zabbix_url,data=host_info,zabbix_header=self.zabbix_header)
109         if add_host['result']['hostids']:
110             print "增加被监控主机成功,主机id : %s"%(add_host['result']['hostids'])
111 
112     def Del_Host(self,host_id):
113         self.host_id = host_id
114         auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
115         del_host_info = json.dumps({
116             "jsonrpc": "2.0",
117             "method": "host.delete",
118             "params": [
119                 self.host_id,
120             ],
121             "auth": auth_code,
122             "id": auth_id
123         })
124         host_del = Zabbix_Url_Request(self.zabbix_url,del_host_info,self.zabbix_header)
125         print host_del
126         #if host_del['error']
127 
128         if host_del['result']['hostids'] == self.host_id:
129             print 'id为%s主机删除成功!!!'%self.host_id
130 
131     def Update_Host_Ienventory(self,host_id,host_inventory,*args,**kwargs):
132         self.host_id = host_id
133         self.host_inventory = host_inventory
134         auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=self.zabbix_url,zabbix_header=self.zabbix_header)
135         host_msg = {}
136         host_msg['hostid'] = self.host_id
137         host_msg['inventory_mode'] = 0
138         host_msg['inventory'] = self.host_inventory
139 
140         update_msg = json.dumps(
141             {
142                 "jsonrpc": "2.0",
143                 "method": "host.update",
144                 "params": host_msg,
145                 "auth": auth_code,
146                 "id": auth_id
147             }
148         )
149         update_host_ienventory = Zabbix_Url_Request(zabbix_url=self.zabbix_url,data=update_msg,zabbix_header=self.zabbix_header)
150         print update_host_ienventory
151 
152 def Get_Group_Id(group_name,zabbix_url,zabbix_header,*args,**kwargs):
153     '''
154     通过组名获取组id
155     :param group_name:  组名
156     :return:
157     '''
158     auth_code, auth_id = Zabbix_Auth_Code(zabbix_url=zabbix_url,zabbix_header=zabbix_header)
159     group_info = json.dumps({
160         "jsonrpc": "2.0",
161         "method": "hostgroup.get",
162         "params": {
163             "output": "extend",
164             "filter": {
165                 "name": [
166                    group_name,
167                 ]
168             }
169         },
170         "auth":auth_code,
171         "id": auth_id
172     })
173     groups_result = Zabbix_Url_Request(zabbix_url=zabbix_url,data=group_info, zabbix_header=zabbix_header)
174     #print groups_result['result'][0]['groupid']
175     return groups_result['result'][0]['groupid']
176 
177 
178 def Get_Template_Id(template_name,zabbix_url,zabbix_header,*args,**kwargs):
179     '''
180     通过模板名获取组id
181     :param template_name: 模板名
182     :return:
183     '''
184     auth_code,auth_id = Zabbix_Auth_Code(zabbix_url=zabbix_url,zabbix_header=zabbix_header)
185     template_info = json.dumps({
186             "jsonrpc": "2.0",
187             "method": "template.get",
188             "params": {
189                 "output": "extend",
190                 "filter": {
191                     "host": [
192                         template_name
193                     ]
194                 }
195             },
196             "auth": auth_code,
197             "id": auth_id
198         })
199     template_result = Zabbix_Url_Request(zabbix_url=zabbix_url,date=template_info,zabbix_header= zabbix_header)
200     #print template_result['result'][0]['templateid']
201     return template_result['result'][0]['templateid']

 

index.py 程序入口

 1 #/usr/bin/env python
 2 # encoding: utf-8
 3 import yaml
 4 from host_info import Host_Action,Get_Group_Id,Get_Template_Id
 5 import sys
 6 reload(sys)
 7 sys.setdefaultencoding('utf8')
 8 
 9 if __name__ == '__main__':
10     try:
11         with open('config.ymal') as f:
12             result = yaml.load(f)
13         result_zabbix_info = result['Zabbix_Config']
14         zabbix_url = result_zabbix_info['zabbix_url']
15         zabbix_header = result_zabbix_info['zabbix_header']
16 
17         #删除主机
18         host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84',
19                            visible_name='t1')
20         host_id = host.Get_Host_Id()
21         host.Del_Host(host_id)
22         #增加主机不带资产
23         host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84',visible_name='t1')
24         host.Add_Host(host_ip='192.168.1.84')
25 
26         #获取指定主机的hostid
27         host = Host_Action(zabbix_url=zabbix_url,zabbix_header=zabbix_header,host_name='192.168.1.84')
28         host_id = host.Get_Host_Id()
29         print '主机192.168.1.84的id是: %s'%host_id
30 
31         #获取指定模本的id
32         t_id = Get_Template_Id(template_name='Template OS Linux',zabbix_header=zabbix_header,zabbix_url=zabbix_url)
33         print "模板Template OS Linux的id是:%s"%t_id
34 
35         #获取指定组的id
36         Get_Group_Id(group_name='Linux servers',zabbix_header=zabbix_header,zabbix_url=zabbix_url)
37         print "组Linux servers的id是:%s" % t_id
38 
39 
40 
41         host_inventory = {
42             "type": "Linux Server",
43             "name": "xxxxxxx",
44             "os": "centos7.2",
45             "os_full": "RedHat Centos 7.2",
46             "os_short": "Centos 7.2",
47             "serialno_a": "f729d3fa-fd53-4c5f-8998-67869dad349a",
48             "macaddress_a": "00:16:3e:03:af:a0",
49             "hardware_full": "cpu: 4c; 内存: 8G; 硬盘: 20G",
50             "software_app_a": "docker",
51             "software_app_b": "zabbix agent",
52             "software_full": "docker zabbix-server ntpd",
53             "contact": "xxx",  # 联系人
54             "location": "阿里云 华北二",  # 位置
55             "vendor": "阿里云",  # 提供者
56             "contract_number": "",  # 合同编号
57             "installer_name": "xx 手机: xxxxxxxxxx",  # 安装名称
58             "deployment_status": "prod",
59             "host_networks": "192.168.1.179",
60             "host_netmask": "255.255.255.0",
61             "host_router": "192.168.1.1",
62             "date_hw_purchase": "2016-07-01",  # 硬件购买日期
63             "date_hw_install": "2016-07-01",  # 硬件购买日期
64             "date_hw_expiry": "0000-00-00",  # 硬件维修过期
65             "date_hw_expiry": "0000-00-00",  # 硬件维修过期
66             "date_hw_decomm": "0000-00-00",  # 硬件报废时间
67             "site_city": "北京",
68             "site_state": "北京",
69             "site_country": "中国",
70             "site_zip": "100000",  # 邮编
71             "site_rack": "",  # 机架
72         }
73 
74         #添加带资产的主机
75         host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84')
76         host_id = host.Get_Host_Id(host_inventory=host_inventory,flag=1)
77 
78         # 删除主机
79         host = Host_Action(zabbix_url=zabbix_url, zabbix_header=zabbix_header, host_name='192.168.1.84',
80                            visible_name='t1')
81         host_id = host.Get_Host_Id()
82         host.Del_Host(host_id)
83 
84     except Exception,e:
85         print e

部分执行结果如下:

增加被监控主机成功,主机id : [u'10116']
主机192.168.1.84的id是: 10115
模板Template OS Linux的id是:10001

组Linux servers的id是:10001

资产情况如下图:


 

posted @ 2016-11-17 14:53  chen_vbird  阅读(3419)  评论(0编辑  收藏  举报