python批量添加zabbix Screens的两个脚本分享

释放双眼,带上耳机,听听看~!

前言

在最初搭建公司监控系统的时候,最头疼的是需要把同类项目组的相同图形添加到一个Screens,由于只能一个一个的添加,非常耗时耗经历。

下面分享两个脚本来解决这个头疼的问题。

1.将单个主机的所有图形添加到一个Screens

使用方法


1
2
3
4
5
6
7
8
1#更改main()函数里的url、username、password
2
3#参数一:主机名
4
5#参数二:筛选图名称
6
7python zabbix_screen_host.py 'zabbixserver' 'zabbixserver'
8

zabbix_screen_host.py脚本内容


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
1#!/usr/bin/env python
2#zabbix_screen_host.py
3import urllib2
4import json
5import argparse
6def authenticate(url, username, password):
7 values = {'jsonrpc': '2.0',
8 'method': 'user.login',
9 'params': {
10  'user': username,
11  'password': password
12 },
13 'id': '0'
14 }
15 data = json.dumps(values)
16 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
17 response = urllib2.urlopen(req, data)
18 output = json.loads(response.read())
19 try:
20 message = output['result']
21 except:
22 message = output['error']['data']
23 print message
24 quit()
25 return output['result']
26def getGraph(hostname, url, auth, graphtype, dynamic, columns):
27 if (graphtype == 0):
28 selecttype = ['graphid']
29 select = 'selectGraphs'
30 if (graphtype == 1):
31 selecttype = ['itemid', 'value_type']
32 select = 'selectItems'
33 values = {'jsonrpc': '2.0',
34 'method': 'host.get',
35 'params': {
36  select: selecttype,
37  'output': ['hostid', 'host'],
38  'searchByAny': 1,
39  'filter': {
40  'host': hostname
41  }
42 },
43 'auth': auth,
44 'id': '2'
45 }
46 data = json.dumps(values)
47 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
48 response = urllib2.urlopen(req, data)
49 host_get = response.read()
50 output = json.loads(host_get)
51 # print json.dumps(output)
52 graphs = []
53 if (graphtype == 0):
54 for i in output['result'][0]['graphs']:
55 graphs.append(i['graphid'])
56 if (graphtype == 1):
57 for i in output['result'][0]['items']:
58 if int(i['value_type']) in (0, 3):
59 graphs.append(i['itemid'])
60 graph_list = []
61 x = 0
62 y = 0
63 for graph in graphs:
64 graph_list.append({
65 "resourcetype": graphtype,
66 "resourceid": graph,
67 "width": "500",
68 "height": "100",
69 "x": str(x),
70 "y": str(y),
71 "colspan": "1",
72 "rowspan": "1",
73 "elements": "0",
74 "valign": "0",
75 "halign": "0",
76 "style": "0",
77 "url": "",
78 "dynamic": str(dynamic)
79 })
80 x += 1
81 if x == columns:
82 x = 0
83 y += 1
84 return graph_list
85def screenCreate(url, auth, screen_name, graphids, columns):
86 # print graphids
87 if len(graphids) % columns == 0:
88 vsize = len(graphids) / columns
89 else:
90 vsize = (len(graphids) / columns) + 1
91 values = {"jsonrpc": "2.0",
92 "method": "screen.create",
93 "params": [{
94  "name": screen_name,
95  "hsize": columns,
96  "vsize": vsize,
97  "screenitems": []
98 }],
99 "auth": auth,
100 "id": 2
101 }
102 for i in graphids:
103 values['params'][0]['screenitems'].append(i)
104 data = json.dumps(values)
105 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
106 response = urllib2.urlopen(req, data)
107 host_get = response.read()
108 output = json.loads(host_get)
109 try:
110 message = output['result']
111 except:
112 message = output['error']['data']
113 print json.dumps(message)
114
115def main():
116 url = 'http://zabbixip/zabbix/api_jsonrpc.php'
117 username = "***"
118 password = "***"
119 parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')
120 parser.add_argument('hostname', metavar='H', type=str,
121  help='Zabbix Host to create screen from')
122 parser.add_argument('screenname', metavar='N', type=str,
123  help='Screen name in Zabbix. Put quotes around it if you want spaces in the name.')
124 parser.add_argument('-c', dest='columns', type=int, default=3,
125  help='number of columns in the screen (default: 3)')
126 parser.add_argument('-d', dest='dynamic', action='store_true',
127  help='enable for dynamic screen items (default: disabled)')
128 parser.add_argument('-t', dest='screentype', action='store_true',
129  help='set to 1 if you want item simple graphs created (default: 0, regular graphs)')
130 args = parser.parse_args()
131 hostname = args.hostname
132 screen_name = args.screenname
133 columns = args.columns
134 dynamic = (1 if args.dynamic else 0)
135 screentype = (1 if args.screentype else 0)
136 auth = authenticate(url, username, password)
137 graphids = getGraph(hostname, url, auth, screentype, dynamic, columns)
138 print "Screen Name: " + screen_name
139 print "Total Number of Graphs: " + str(len(graphids))
140 screenCreate(url, auth, screen_name, graphids, columns)
141if __name__ == '__main__':
142 main()
143

2.将同组主机的同一图形添加到一个Screens

使用方法


1
2
3
4
5
6
7
8
9
10
11
12
1#更改main()函数里的url、username、password
2
3#-g :组名称
4
5#-G:图形名称
6
7#-n :筛选(screen)图名称
8
9#-c : 一行有多少图形
10
11python zabbix_screen_group.py -g 'zabbix' -G 'icmp-ping' -n 'zabbix-icmp-ping' -c 2
12

zabbix_screen_group.py脚本内容


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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
1#!/usr/bin/env python
2import urllib2
3import sys
4import json
5import argparse
6
7#定义通过HTTP方式访问API地址的函数,后面每次请求API的各个方法都会调用这个函数
8def requestJson(url,values):
9 data = json.dumps(values)
10 req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
11 response = urllib2.urlopen(req, data)
12 output = json.loads(response.read())
13# print output
14 try:
15 message = output['result']
16 except:
17 message = output['error']['data']
18 print message
19 quit()
20
21 return output['result']
22
23#API接口认证的函数,登录成功会返回一个Token
24def authenticate(url, username, password):
25 values = {'jsonrpc': '2.0',
26  'method': 'user.login',
27  'params': {
28   'user': username,
29   'password': password
30  },
31  'id': '0'
32  }
33 idvalue = requestJson(url,values)
34 return idvalue
35
36#定义更加主机分组名称获取各个hostid的函数
37def getHosts(groupname,url,auth):
38 host_list = []
39 values = {'jsonrpc': '2.0',
40  'method': 'hostgroup.get',
41  'params': {
42   'output': 'extend',
43   'filter': {
44   'name': groupname
45   },
46
47   'selectHosts' : ['hostid','host'],
48  },
49  'auth': auth,
50  'id': '2'
51  }
52 output = requestJson(url,values)
53 for host in output[0]['hosts']:
54 host_list.append(host['hostid'])
55 return host_list
56
57#定义获取graphid的函数
58def getGraphs(host_list,name_list, url, auth, columns, graphtype=0 ,dynamic=0):
59 if (graphtype == 0):
60 selecttype = ['graphid']
61 select = 'selectGraphs'
62 if (graphtype == 1):
63 selecttype = ['itemid', 'value_type']
64 select = 'selectItems'
65 values=({'jsonrpc' : '2.0',
66  'method' : 'graph.get',
67  'params' : {
68   'output' : ['graphid','name'],
69   select : [selecttype,'name'],
70   'hostids' : host_list,
71   'sortfield' : 'name',
72   'filter' : {
73    'name' : name_list,
74
75    },
76   },
77  'auth' : auth,
78  'id' : 3
79  })
80 output = requestJson(url,values)
81 bb = sorted(output,key = lambda x:x['graphid'])
82 graphs = []
83 if (graphtype == 0):
84 for i in bb:
85  print i
86  graphs.append(i['graphid'])
87 if (graphtype == 1):
88 for i in bb:
89  if int(i['value_type']) in (0, 3):
90  graphs.append(i['itemid'])
91
92 graph_list = []
93 x = 0
94 y = 0
95 for graph in graphs:
96 print "x is " + str(x)
97 print "y is " + str(y)
98 graph_list.append({
99  "resourcetype": graphtype,
100  "resourceid": graph,
101  "width": "500",
102  "height": "100",
103  "x": str(x),
104  "y": str(y),
105  "colspan": "1",
106  "rowspan": "1",
107  "elements": "0",
108  "valign": "0",
109  "halign": "0",
110  "style": "0",
111  "url": "",
112  "dynamic": str(dynamic)
113 })
114 x += 1
115# print type(x)
116# print type(columns)
117 if x == int(columns):
118  x = 0
119  y += 1
120# print graph_list
121 return graph_list
122
123#定义创建screen的函数
124def screenCreate(url, auth, screen_name, graphids, columns):
125 columns = int(columns)
126 if len(graphids) % columns == 0:
127 vsize = len(graphids) / columns
128 else:
129 vsize = (len(graphids) / columns) + 1
130
131#先使用screen.get判断给定的screen name是否存在
132 values0 = {
133  "jsonrpc" : "2.0",
134  "method" : "screen.get",
135  "params" : {
136   "output" : "extend",
137   "filter" : {
138   "name" : screen_name,
139    }
140    },
141  "auth" : auth,
142  "id" : 2
143  }
144 values = {
145  "jsonrpc": "2.0",
146  "method": "screen.create",
147  "params": {
148   "name": screen_name,
149   "hsize": columns,
150   "vsize": vsize,
151   "screenitems": []
152  },
153  "auth": auth,
154  "id": 2
155  }
156 output0 = requestJson(url,values0)
157 print output0
158
159#如果给定的screen name不存在则直接创建screen
160 if output0 == []:
161 print "The Given Screen Name Not Exists"
162 print "Creating Screen %s" %screen_name
163 for i in graphids:
164  values['params']['screenitems'].append(i)
165 output = requestJson(url,values)
166 else:
167
168
169#如果给定的screen name已经存在,直接创建screen是不行的,
170#要么先使用screen.delete把原来的screen删除掉,然后再创建,
171#要么直接使用screen.update更新原来那个screen,
172#使用screen.delete会产生新的screenid,
173#使用screen.update比较合理一点。
174 print "The Given Screen Name Already Exists"
175 update_screenid=output0[0]["screenid"]
176 print update_screenid
177 print "Updating Screen Name %s Screen ID %s" %(screen_name,update_screenid)
178 values1 = {
179  "jsonrpc" : "2.0",
180  "method" : "screen.update",
181  "params" : {
182   "screenid" : update_screenid,
183   "screenitems": []
184    },
185  "auth" : auth,
186  "id" : 2
187   }
188 output1 = requestJson(url,values1)
189 print output1
190 print "Updating Screen Name %s" %screen_name
191 for i in graphids:
192  values1['params']['screenitems'].append(i)
193 output = requestJson(url,values1)
194
195def main():
196 url = 'http://zabbixip/zabbix/api_jsonrpc.php'
197 username = '****'
198 password = '****'
199 auth = authenticate(url, username, password)
200 host_list = getHosts(groupname,url,auth)
201 print host_list
202 graph_ids = getGraphs(host_list,graphname, url, auth, columns)
203 screenCreate(url, auth, screenname, graph_ids, columns)
204if __name__ == '__main__':
205 parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')
206 parser.add_argument('-G', dest='graphname', nargs='+',metavar=('grah name'),
207   help='Zabbix Host Graph to create screen from')
208 parser.add_argument('-H', dest='hostname', nargs='+',metavar=('10.19.111.145'),
209   help='Zabbix Host to create screen from')
210 parser.add_argument('-g', dest='groupname', nargs='+',metavar=('linux server'),
211   help='Zabbix Group to create screen from')
212 parser.add_argument('-n', dest='screenname', type=str,
213   help='Screen name in Zabbix. Put quotes around it if you want spaces in the name.')
214 parser.add_argument('-c', dest='columns', type=int,
215   help='number of columns in the screen')
216 args = parser.parse_args()
217 print args
218 hostname = args.hostname
219 groupname = args.groupname
220 screenname = args.screenname
221 columns = args.columns
222 graphname = args.graphname
223 if columns is None:
224 columns = len(graphname)
225# print columns
226 main()
227

总结

以上就是这篇文章的全部内容了,希望本文的内容的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++异常

2022-1-11 12:36:11

安全技术

python迭代器和生成器

2022-1-12 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索