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,如需转载请自行联系原作者

相关文章
|
8月前
|
缓存 监控 前端开发
顺企网 API 开发实战:搜索 / 详情接口从 0 到 1 落地(附 Elasticsearch 优化 + 错误速查)
企业API开发常陷参数、缓存、错误处理三大坑?本指南拆解顺企网双接口全流程,涵盖搜索优化、签名验证、限流应对,附可复用代码与错误速查表,助你2小时高效搞定开发,提升响应速度与稳定性。
|
8月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
8月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
9月前
|
JSON 前端开发 API
如何调用体育数据足篮接口API
本文介绍如何调用体育数据API:首先选择可靠服务商并注册获取密钥,接着阅读文档了解基础URL、端点、参数及请求头,然后使用Python等语言发送请求、解析JSON数据,最后将数据应用于Web、App或分析场景,同时注意密钥安全、速率限制与错误处理。
968 152
|
8月前
|
Cloud Native 算法 API
Python API接口实战指南:从入门到精通
🌟蒋星熠Jaxonic,技术宇宙的星际旅人。深耕API开发,以Python为舟,探索RESTful、GraphQL等接口奥秘。擅长requests、aiohttp实战,专注性能优化与架构设计,用代码连接万物,谱写极客诗篇。
1744 1
Python API接口实战指南:从入门到精通
|
8月前
|
人工智能 自然语言处理 测试技术
Apipost智能搜索:只需用业务语言描述需求,就能精准定位目标接口,API 搜索的下一代形态!
在大型项目中,API 数量庞大、命名不一,导致“找接口”耗时费力。传统工具依赖关键词搜索,难以应对语义模糊或命名不规范的场景。Apipost AI 智能搜索功能,支持自然语言查询,如“和用户登录有关的接口”,系统可理解语义并精准匹配目标接口。无论是新人上手、模糊查找还是批量定位,都能大幅提升检索效率,降低协作成本。从关键词到语义理解,智能搜索让开发者少花时间找接口,多专注核心开发,真正实现高效协作。
|
8月前
|
存储 缓存 算法
亚马逊 SP-API 深度开发:关键字搜索接口的购物意图挖掘与合规竞品分析
本文深度解析亚马逊SP-API关键字搜索接口的合规调用与商业应用,涵盖意图识别、竞品分析、性能优化全链路。通过COSMO算法解析用户购物意图,结合合规技术方案提升关键词转化率,助力卖家实现数据驱动决策,安全高效优化运营。
|
9月前
|
人工智能 运维 监控
阿里云 API 聚合实战:破解接口碎片化难题,3 类场景方案让业务响应提速 60%
API聚合破解接口碎片化困局,助力开发者降本增效。通过统一中间层整合微服务、第三方接口与AI模型,实现调用次数减少60%、响应提速70%。阿里云实测:APISIX+函数计算+ARMS监控组合,支撑百万级并发,故障定位效率提升90%。
691 0
|
9月前
|
JSON 自然语言处理 监控
淘宝关键词搜索与商品详情API接口(JSON数据返回)
通过商品ID(num_iid)获取商品全量信息,包括SKU规格、库存、促销活动、卖家信息、详情页HTML等。
|
9月前
|
人工智能 API 监控
告别多接口拼凑!阿里云 API 模型聚合实现技术能力协同跃迁
API聚合整合400+国内外AI模型,统一接口、屏蔽差异,降低开发与维护成本,提升效率与系统稳定性,助力开发者高效应对多API调用困境。
999 0