python调用zabbix的api接口添加主机、查询组、主机、模板

简介:

   zabbix有一个API接口,可以调用这些几口来自动添加主机,查询zabbix中监控的主机,监控的模板、监控的主机组等信息,使用也非常的方便。以下是用python调用zabbix的API接口来实现上述功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import  json
import  urllib2
import  sys
class  zabbixtools:
     def  __init__( self ):
         self .url  =  "http://192.168.100.200/zabbix/api_jsonrpc.php"
         self .header  =  { "Content-Type" "application/json" }
         self .authID  =  self .user_login()
     def  user_login( self ):
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "user.login" ,
                     "params" : {
                         "user" "Admin" ,
                         "password" "zabbix"
                         },
                     "id" 0
                     })
         request  =  urllib2.Request( self .url,data)
         for  key  in  self .header:
             request.add_header(key, self .header[key])
         try :
             result  =  urllib2.urlopen(request)
         except  URLError as e:
             print  "Auth Failed, Please Check Your Name And Password:" ,e.code
         else :
             response  =  json.loads(result.read())
             result.close()
             authID  =  response[ 'result' ]
             return  authID
     def  get_data( self ,data,hostip = ""):
         request  =  urllib2.Request( self .url,data)
         for  key  in  self .header:
             request.add_header(key, self .header[key])
         try :
             result  =  urllib2.urlopen(request)
         except  URLError as e:
             if  hasattr (e,  'reason' ):
                 print  'We failed to reach a server.'
                 print  'Reason: ' , e.reason
             elif  hasattr (e,  'code' ):
                 print  'The server could not fulfill the request.'
                 print  'Error code: ' , e.code
             return  0
         else :
             response  =  json.loads(result.read())
             result.close()
             return  response
     def  host_get( self ,hostip):
         #hostip = raw_input("\033[1;35;40m%s\033[0m" % 'Enter Your Check Host:Host_ip :')
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "host.get" ,
                     "params" : {
                         "output" :[ "hostid" , "name" , "status" , "host" ],
                         "filter" : { "host" : [hostip]}
                         },
                     "auth" self .authID,
                     "id" 1
                 })
         res  =  self .get_data(data)[ 'result' ]
         if  (res ! =  0 and  ( len (res) ! =  0 ):
             #for host in res:
             host  =  res[ 0 ]
             if  host[ 'status' = =  '1' :
                 print  "\t" , "\033[1;31;40m%s\033[0m"  %  "Host_IP:" , "\033[1;31;40m%s\033[0m"  %  host[ 'host' ].ljust( 15 ), '\t' , "\033[1;31;40m%s\033[0m"  %  "Host_Name:" , "\033[1;31;40m%s\033[0m"  %  host[ 'name' ].encode( 'GBK' ), '\t' , "\033[1;31;40m%s\033[0m"  %  u '未在监控状态' .encode( 'GBK' )
                 return  host[ 'hostid' ]
             elif  host[ 'status' = =  '0' :
                 print  "\t" , "\033[1;32;40m%s\033[0m"  %  "Host_IP:" , "\033[1;32;40m%s\033[0m"  %  host[ 'host' ].ljust( 15 ), '\t' , "\033[1;32;40m%s\033[0m"  %  "Host_Name:" , "\033[1;32;40m%s\033[0m"  %  host[ 'name' ].encode( 'GBK' ), '\t' , "\033[1;32;40m%s\033[0m"  %  u '在监控状态' .encode( 'GBK' )
                 return  host[ 'hostid' ]
             print
         else :
             print  '\t' , "\033[1;31;40m%s\033[0m"  %  "Get Host Error or cannot find this host,please check !"
             return  0
     def  host_del( self ):
         hostip  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter Your Check Host:Host_ip :' )
         hostid  =  self .host_get(hostip)
         if  hostid  = =  0 :
             print  '\t' , "\033[1;31;40m%s\033[0m"  %  "This host cannot find in zabbix,please check it !"
             sys.exit()
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "host.delete" ,
                     "params" : [{ "hostid" : hostid}],
                     "auth" self .authID,
                     "id" 1
                 })
         res  =  self .get_data(data)[ 'result' ]
         if  'hostids'  in  res.keys():
             print  "\t" , "\033[1;32;40m%s\033[0m"  %  "Delet Host:%s success !"  %  hostip
         else :
             print  "\t" , "\033[1;31;40m%s\033[0m"  %  "Delet Host:%s failure !"  %  hostip
     def  hostgroup_get( self ):
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "hostgroup.get" ,
                     "params" : {
                         "output" "extend" ,
                         },
                     "auth" self .authID,
                     "id" 1 ,
                     })
         res  =  self .get_data(data)
         if  'result'  in  res.keys():
             res  =  res[ 'result' ]
             if  (res ! = 0 or  ( len (res) ! =  0 ):
                 print  "\033[1;32;40m%s\033[0m"  %  "Number Of Group: " "\033[1;31;40m%d\033[0m"  %  len (res)
                 for  host  in  res:
                     print  "\t" , "HostGroup_id:" ,host[ 'groupid' ], "\t" , "HostGroup_Name:" ,host[ 'name' ].encode( 'GBK' )
                 print
         else :
             print  "Get HostGroup Error,please check !"
     def  template_get( self ):
         data  =  json.dumps(
                 {
                     "jsonrpc" "2.0" ,
                     "method" "template.get" ,
                     "params" : {
                         "output" "extend" ,
                         },
                     "auth" self .authID,
                     "id" 1 ,
                     })
         res  =  self .get_data(data) #['result']
         if  'result'  in  res.keys():
             res  =  res[ 'result' ]
             if  (res ! = 0 or  ( len (res) ! =  0 ):
                 print  "\033[1;32;40m%s\033[0m"  %  "Number Of Template: " "\033[1;31;40m%d\033[0m"  %  len (res)
                 for  host  in  res:
                     print  "\t" , "Template_id:" ,host[ 'templateid' ], "\t" , "Template_Name:" ,host[ 'name' ].encode( 'GBK' )
                 print
         else :
             print  "Get Template Error,please check !"
     def  host_create( self ):
         hostip  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter your:Host_ip :' )
         groupid  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter your:Group_id :' )
         templateid  =  raw_input ( "\033[1;35;40m%s\033[0m"  %  'Enter your:Tempate_id :' )
         g_list = []
         t_list = []
         for  in  groupid.split( ',' ):
             var  =  {}
             var[ 'groupid' =  i
             g_list.append(var)
         for  in  templateid.split( ',' ):
             var  =  {}
             var[ 'templateid' =  i
             t_list.append(var)
         if  hostip  and  groupid  and  templateid:
             data  =  json.dumps(
                     {
                         "jsonrpc" "2.0" ,
                         "method" "host.create" ,
                         "params" : {
                             "host" : hostip,
                             "interfaces" : [
                                 {
                                     "type" 1 ,
                                     "main" 1 ,
                                     "useip" 1 ,
                                     "ip" : hostip,
                                     "dns" : "",
                                     "port" "10050"
                                 }
                             ],
                             "groups" : g_list,
                             "templates" : t_list,
                     },
                         "auth" self .authID,
                         "id" 1 ,
                         })
             res  =  self .get_data(data,hostip)
             if  'result'  in  res.keys():
                 res  =  res[ 'result' ]
                 if  'hostids'  in  res.keys():
                     print  "\033[1;32;40m%s\033[0m"  %  "Create host success"
             else :
                 print  "\033[1;31;40m%s\033[0m"  %  "Create host failure: %s"  %  res[ 'error' ][ 'data' ]
         else :
             print  "\033[1;31;40m%s\033[0m"  %  "Enter Error: ip or groupid or tempateid is NULL,please check it !"
def  main():
     test  =  zabbixtools()
     #test.template_get()
     #test.hostgroup_get()
     #test.host_get()
     test.host_del()
     #test.host_create()
if  __name__  = =  "__main__" :
     main()

   相关的材料的可以参考官方文档。这个只是一些功能模块,包含获取主机,主机组、模板、删除主机等功能,可以根据需要进行调整,实现zabbix的批量化和自动化管理。因为是在linux运行,所以设置了输出终端的字体颜色方便区分,如果不需要,自行删除即可。



本文转自 lover00751CTO博客,原文链接:http://blog.51cto.com/wangwei007/1249770,如需转载请自行联系原作者

相关文章
|
27天前
|
Python
Python实现简易天气查询系统
Python实现简易天气查询系统
28 4
|
1月前
|
数据采集 JSON API
如何实现高效率超简洁的实时数据采集?——Python实战电商数据采集API接口
你是否曾为获取重要数据而感到困扰?是否因为数据封锁而无法获取所需信息?是否因为数据格式混乱而头疼?现在,所有这些问题都可以迎刃而解。让我为大家介绍一款强大的数据采集API接口。
|
1月前
|
JSON API 数据库
解释如何在 Python 中实现 Web 服务(RESTful API)。
解释如何在 Python 中实现 Web 服务(RESTful API)。
26 0
|
1月前
|
缓存 API 定位技术
使用Python调用百度地图API实现地址查询
使用Python调用百度地图API实现地址查询
100 0
|
1天前
|
测试技术 API 网络架构
Python的api自动化测试 编写测试用例
【4月更文挑战第18天】使用Python进行API自动化测试,可以结合`requests`库发送HTTP请求和`unittest`(或`pytest`)编写测试用例。以下示例: 1. 安装必要库:`pip install requests unittest` 2. 创建`test_api.py`,导入库,定义基础URL。 3. 创建继承自`unittest.TestCase`的测试类,包含`setUp`和`tearDown`方法。 4. 编写测试用例,如`test_get_users`,检查响应状态码和内容。 5. 运行测试:`python -m unittest test_api.py`
7 2
|
1天前
|
JSON 测试技术 API
Python的Api自动化测试使用HTTP客户端库发送请求
【4月更文挑战第18天】在Python中进行HTTP请求和API自动化测试有多个库可选:1) `requests`是最流行的选择,支持多种请求方法和内置JSON解析;2) `http.client`是标准库的一部分,适合需要低级别控制的用户;3) `urllib`提供URL操作,适用于复杂请求;4) `httpx`拥有类似`requests`的API,提供现代特性和异步支持。根据具体需求选择,如多数情况`requests`已足够。
6 3
|
1天前
|
人工智能 机器人 API
【Python+微信】【企业微信开发入坑指北】3. 如何利用企业微信API给微信群推送消息
【Python+微信】【企业微信开发入坑指北】3. 如何利用企业微信API给微信群推送消息
4 0
|
1月前
|
数据采集 搜索推荐 数据挖掘
使用Python制作一个批量查询搜索排名的SEO免费工具
最近工作中需要用上 Google SEO(搜索引擎优化),有了解过的朋友们应该都知道SEO必不可少的工作之一就是查询关键词的搜索排名。关键词少的时候可以一个一个去查没什么问题,但是到了后期,一个网站都有几百上千的关键词,你再去一个一个查,至少要花费数小时的时间。 虽然市面上有很多SEO免费或者收费工具,但免费的基本都不能批量查,网上免费的最多也就只能10个10个查询,而且查询速度很慢。收费的工具如Ahrefs、SEMrush等以月为单位收费最低也都要上百美刀/月,当然如果觉得价格合适也可以进行购买,毕竟这些工具的很多功能都很实用。今天我给大家分享的这个排名搜索工具基于python实现,当然肯定
40 0
|
1月前
|
JSON API 数据格式
Python中使用API(四)
Python中使用API(四)
20 0
|
1月前
|
JSON API 数据格式
Python中使用API(三)
Python中使用API(三)
18 0

推荐镜像

更多