通過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

資產情況如下圖:

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM