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

相关文章
|
3月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
3月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
4月前
|
缓存 监控 算法
唯品会item_search - 按关键字搜索 VIP 商品接口深度分析及 Python 实现
唯品会item_search接口支持通过关键词、分类、价格等条件检索商品,广泛应用于电商数据分析、竞品监控与市场调研。结合Python可实现搜索、分析、可视化及数据导出,助力精准决策。
|
3月前
|
Cloud Native 算法 API
Python API接口实战指南:从入门到精通
🌟蒋星熠Jaxonic,技术宇宙的星际旅人。深耕API开发,以Python为舟,探索RESTful、GraphQL等接口奥秘。擅长requests、aiohttp实战,专注性能优化与架构设计,用代码连接万物,谱写极客诗篇。
Python API接口实战指南:从入门到精通
|
4月前
|
缓存 监控 算法
苏宁item_get - 获得商品详情接口深度# 深度分析及 Python 实现
苏宁易购item_get接口可实时获取商品价格、库存、促销等详情,支持电商数据分析与竞品监控。需认证接入,遵守调用限制,适用于价格监控、销售分析等场景,助力精准营销决策。(238字)
|
4月前
|
监控 算法 数据安全/隐私保护
唯品会 item_get - 获得 VIP 商品详情接口深度分析及 Python 实现
唯品会item_get接口通过商品ID获取商品详情,支持价格、库存、促销等数据抓取,适用于电商分析、竞品监控与价格追踪,结合Python实现可高效完成数据获取、分析与可视化,助力精准营销决策。
|
4月前
|
供应链 监控 算法
VVICitem_get - 根据 ID 取商品详情接口深度分析及 Python 实现
VVIC(搜款网)是国内领先的服装批发电商平台,其item_get接口支持通过商品ID获取详尽的商品信息,涵盖价格、规格、库存、图片及店铺数据,助力商家高效开展市场分析、竞品监控与采购决策。
|
4月前
|
JSON 缓存 供应链
电子元件 item_search - 按关键字搜索商品接口深度分析及 Python 实现
本文深入解析电子元件item_search接口的设计逻辑与Python实现,涵盖参数化筛选、技术指标匹配、供应链属性过滤及替代型号推荐等核心功能,助力高效精准的电子元器件搜索与采购决策。
|
4月前
|
缓存 供应链 芯片
电子元件类商品 item_get - 商品详情接口深度分析及 Python 实现
电子元件商品接口需精准返回型号参数、规格属性、认证及库存等专业数据,支持供应链管理与采购决策。本文详解其接口特性、数据结构与Python实现方案。

热门文章

最新文章