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

相关文章
|
11月前
|
缓存 API 网络架构
淘宝item_search_similar - 搜索相似的商品API接口,用python返回数据
淘宝联盟开放平台中,可通过“物料优选接口”(taobao.tbk.dg.optimus.material)实现“搜索相似商品”功能。该接口支持根据商品 ID 获取相似推荐商品,并返回商品信息、价格、优惠等数据,适用于商品推荐、比价等场景。本文提供基于 Python 的实现示例,包含接口调用、数据解析及结果展示。使用时需配置淘宝联盟的 appkey、appsecret 和 adzone_id,并注意接口调用频率限制和使用规范。
|
9月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
11月前
|
JSON 缓存 API
深度分析淘宝API接口,用Python脚本实现
本内容深入解析淘宝开放平台 API 的接口设计与 Python 实现,涵盖接口体系、认证机制、签名规则及限流策略,并提供完整的 Python 调用框架,适用于电商系统对接与自动化运营。
|
JSON API 开发者
天猫商品详情API接口技术解析与Python实现
天猫商品详情API(tmall.item_get)通过商品ID获取商品标题、价格、库存、图片、SKU及评价等详细信息,支持HTTP请求与JSON格式返回,适用于电商数据分析与运营。本文提供Python调用示例,实现快速接入与数据解析。
|
监控 供应链 数据挖掘
淘宝商品详情API接口解析与 Python 实战指南
淘宝商品详情API接口是淘宝开放平台提供的编程工具,支持开发者获取商品详细信息,包括基础属性、价格、库存、销售策略及卖家信息等。适用于电商数据分析、竞品分析与价格策略优化等场景。接口功能涵盖商品基础信息、详情描述、图片视频资源、SKU属性及评价统计的查询。通过构造请求URL和签名,可便捷调用数据。典型应用场景包括电商比价工具、商品数据分析平台、供应链管理及营销活动监控等,助力高效运营与决策。
534 26
|
11月前
|
JSON API 数据安全/隐私保护
【干货满满】分享淘宝API接口到手价,用python脚本实现
淘宝开放平台通过API可获取商品到手价,结合商品详情与联盟接口实现优惠计算。需使用AppKey、AppSecret及会话密钥认证,调用taobao.tbk.item.info.get接口获取最终价格。代码示例展示签名生成与数据解析流程。
|
10月前
|
JSON API 数据安全/隐私保护
Python采集淘宝评论API接口及JSON数据返回全流程指南
Python采集淘宝评论API接口及JSON数据返回全流程指南
|
XML API 数据格式
深入研究:亚马逊amazon商品详情API接口Python攻略
亚马逊商品详情API(Product Advertising API)让开发者以编程方式获取亚马逊商品信息,如标题、价格、库存、评价等。功能涵盖商品基本信息、购买属性、用户反馈、分类与促销信息。使用时需选择端点(如ItemLookup或ItemSearch)、构建请求、发送至服务器并处理响应数据(JSON/XML格式),同时做好错误处理。适合电商应用开发与数据分析。
|
JSON 监控 API
深入研究:shopee商品详情API接口Python攻略
Shopee 商品详情 API 是用于获取 Shopee 平台商品详细信息的接口,支持开发者提取商品标题、价格、库存、描述和图片等多维度数据。该接口适用于电商数据分析、比价工具开发及商品监控等场景。请求方式为 GET,需提供 itemid(商品 ID)和 shopid(店铺 ID),返回格式为 JSON。部分功能可能需要 API 密钥或访问令牌认证。以马来西亚站点为例,URL 为 shopee.com.myapi/v4/item/get,不同国家站点域名可能有所不同。
|
JSON API 数据格式
深入浅出:微店商品详情API接口Python攻略
本教程介绍如何使用Python与微店商品详情API交互。首先,确保安装`requests`库(`pip install requests`)。接着,在微店开发者平台注册应用以获取API访问权限。然后,通过编写Python代码调用API,示例函数`get_weidian_product_detail`可传入商品ID和AppKey获取商品详情(如名称、价格、图片等)。最后,处理返回的JSON数据并注意错误处理和查阅最新API文档。按此步骤,即可顺利获取商品信息。

热门文章

最新文章