forked from dnaeon/zabbix-ldap-sync
-
Notifications
You must be signed in to change notification settings - Fork 2
/
zabbix-ldap-sync
549 lines (402 loc) · 16.7 KB
/
zabbix-ldap-sync
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
#!/usr/bin/env python
#
# Copyright (c) 2013-2014 Marin Atanasov Nikolov <dnaeon@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer
# in this position and unchanged.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
The zabbix-ldap-sync script is used for syncing LDAP users with Zabbix.
"""
import random
import string
import ConfigParser
import sys
import ldap
import zabbix_api
from docopt import docopt
class LDAPConn(object):
"""
LDAP connector class
Defines methods for retrieving users and groups from LDAP server.
"""
def __init__(self, uri, base, user, passwd):
self.uri = uri
self.base = base
self.ldap_user = user
self.ldap_pass = passwd
def connect(self):
"""
Establish a connection to the LDAP server.
Raises:
SystemExit
"""
self.conn = ldap.initialize(self.uri)
try:
self.conn.simple_bind(self.ldap_user, self.ldap_pass)
except ldap.SERVER_DOWN as e:
raise SystemExit, 'Cannot connect to LDAP server: %s' % e
def disconnect(self):
"""
Disconnect from the LDAP server.
"""
self.conn.unbind()
def get_group_members(self, group):
"""
Retrieves the members of an LDAP group
Args:
group (str): The LDAP group name
Returns:
A list of all users in the LDAP group
"""
attrlist = [group_member_attribute]
filter = group_filter % group
result = self.conn.search_s(base=self.base,
scope=ldap.SCOPE_SUBTREE,
filterstr=filter,
attrlist=attrlist)
if not result:
print '>>> Unable to find group %s, skipping group' % group
return None
# if this is activedirectory, we have to replace each CN with the actual username
if active_directory:
final_listing = []
for members in result:
result_dn = members[0]
result_attrs = members[1]
if "member" in result_attrs:
for member in result_attrs["member"]:
attrlist = ['sAMAccountName']
filter = '(&(objectClass=person)(distinguishedName=%s))' % member
# get the actual LDAP object for each group member
uid = self.conn.search_s(base=self.base,
scope=ldap.SCOPE_SUBTREE,
filterstr=filter,
attrlist=attrlist)
dn, users = uid.pop()
username = users.get('sAMAccountName')
final_listing.append(str(username)[2 : -2])
return final_listing
else:
dn, users = result.pop()
return users[group_member_attribute]
def get_user_email(self, username):
"""
Retrieves the 'mail' attribute of an LDAP user
Args:
username (str): The LDAP username to lookup
Returns:
The user's mail attribute
"""
attrlist = ['mail']
filter = mail_filter % username
result = self.conn.search_s(base=self.base,
scope=ldap.SCOPE_SUBTREE,
filterstr=filter,
attrlist=attrlist)
if not result:
return None
dn, data = result.pop()
mail = data.get('mail')
if not mail:
return None
return mail.pop()
def get_user_sn(self, username):
"""
Retrieves the 'sn' attribute of an LDAP user
Args:
username (str): The LDAP username to lookup
Returns:
The user's surname attribute
"""
attrlist = ['sn']
filter = sn_filter % username
result = self.conn.search_s(base=self.base,
scope=ldap.SCOPE_SUBTREE,
filterstr=filter,
attrlist=attrlist)
if not result:
return None
dn, data = result.pop()
sn = data.get('sn')
if not sn:
return None
return sn.pop()
def get_user_givenname(self, username):
"""
Retrieves the 'givenName' attribute of an LDAP user
Args:
username (str): The LDAP username to lookup
Returns:
The user's given name attribute
"""
attrlist = ['givenName']
filter = givenname_filter % username
result = self.conn.search_s(base=self.base,
scope=ldap.SCOPE_SUBTREE,
filterstr=filter,
attrlist=attrlist)
if not result:
return None
dn, data = result.pop()
name = data.get('givenName')
if not name:
return None
return name.pop()
class ZabbixConn(object):
"""
Zabbix connector class
Defines methods for managing Zabbix users and groups
"""
def __init__(self, server, username, password):
self.server = server
self.username = username
self.password = password
def connect(self):
"""
Establishes a connection to the Zabbix server
Raises:
SystemExit
"""
self.conn = zabbix_api.ZabbixAPI(server=self.server)
try:
self.conn.login(user=self.username, password=self.password)
except zabbix_api.ZabbixAPIException as e:
raise SystemExit, 'Cannot login to Zabbix server: %s' % e
def get_users(self):
"""
Retrieves the existing Zabbix users
Returns:
A list of the existing Zabbix users
"""
req = self.conn.json_obj(method='user.get', params={'output': 'extend'})
result = self.conn.do_request(req)
users = [user['alias'] for user in result['result']]
return users
def get_user_id(self, user):
"""
Retrieves the userid of a specified user
Args:
user (str): The Zabbix username to lookup
Returns:
The userid of the specified user
"""
req = self.conn.json_obj(method='user.get', params={'output': 'extend'})
result = self.conn.do_request(req)
userid = [u['userid'] for u in result['result'] if u['alias'] == user].pop()
return userid
def get_groups(self):
"""
Retrieves the existing Zabbix groups
Returns:
A dict of the existing Zabbix groups and their group ids
"""
req = self.conn.json_obj(method='usergroup.get',
params={'status': 0, 'output': 'extend' })
result = self.conn.do_request(req)
groups = [{'name': group['name'], 'usrgrpid': group['usrgrpid']} for group in result['result']]
return groups
def get_group_members(self, groupid):
"""
Retrieves group members for a Zabbix group
Args:
groupid (int): The group id
Returns:
A list of the Zabbix users for the specified group id
"""
req = self.conn.json_obj(method='user.get', params={'output': 'extend', 'usrgrpids': groupid})
result = self.conn.do_request(req)
users = [user['alias'] for user in result['result']]
return users
def create_group(self, group):
"""
Creates a new Zabbix group
Args:
group (str): The Zabbix group name to create
Returns:
The groupid of the newly created group
"""
req = self.conn.json_obj(method='usergroup.create',
params={'name': group, 'permission': 3})
result = self.conn.do_request(req)
groupid = result['result']['usrgrpids'].pop()
return groupid
def create_user(self, user, groupid):
"""
Creates a new Zabbix user
Args:
user (dict): A dict containing the user details
groupid (int): The groupid for the new user
"""
random_passwd = ''.join(random.sample(string.ascii_letters + string.digits, 32))
user_defaults = { 'autologin': 0, 'type': 1, 'usrgrps': [ { 'usrgrpid': str(groupid) } ], 'passwd': random_passwd}
user.update(user_defaults)
req = self.conn.json_obj(method='user.create',
params=user)
result = self.conn.do_request(req)
return result['result']
def update_user(self, user, groupid):
"""
Adds an existing Zabbix user to a group
Args:
user (dict): A dict containing the user details
groupid (int): The groupid to add the user to
"""
userid = self.get_user_id(user)
req = self.conn.json_obj(method='usergroup.massadd',
params={'usrgrpids': [str(groupid)], 'userids': [str(userid)] })
result = self.conn.do_request(req)
return result['result']
def update_media(self, user, mail):
"""
Adds media (email) to an existing Zabbix user
Args:
user (dict): A dict containing the user details
"""
userid = self.get_user_id(user)
req = self.conn.json_obj(method='user.addmedia',
params={'users': [ { "userid": str(userid) } ],
'medias': { 'mediatypeid': '1',
'sendto': mail,
'active': '0',
'severity': '63',
'period': '1-7,00:00-24:00' }
})
result = self.conn.do_request(req)
return result['result']
def create_missing_groups(self, ldap_groups):
"""
Creates any missing LDAP groups in Zabbix
Args:
ldap_groups (list): A list of LDAP groups to create
"""
missing_groups = set(ldap_groups) - set([g['name'] for g in self.get_groups()])
for eachGroup in missing_groups:
print '>>> Creating Zabbix group %s' % eachGroup
grpid = self.create_group(eachGroup)
print '>>> Group %s created with groupid %s' % (eachGroup, grpid)
def sync_users(self, ldap_uri, ldap_base, ldap_groups, ldap_user, ldap_pass):
"""
Syncs Zabbix with LDAP users
"""
ldap_conn = LDAPConn(ldap_uri, ldap_base, ldap_user, ldap_pass)
ldap_conn.connect()
zabbix_all_users = self.get_users()
for eachGroup in ldap_groups:
ldap_users = ldap_conn.get_group_members(eachGroup)
if not ldap_users:
continue
zabbix_grpid = [g['usrgrpid'] for g in self.get_groups() if g['name'] == eachGroup].pop()
zabbix_group_users = self.get_group_members(zabbix_grpid)
missing_users = set(ldap_users) - set(zabbix_group_users)
# Add missing users
for eachUser in missing_users:
# Create new user if it does not exists already
if eachUser not in zabbix_all_users:
print '>>> Creating user %s, member of Zabbix group %s' % (eachUser, eachGroup)
user = { 'alias': eachUser }
user['name'] = ldap_conn.get_user_givenname(eachUser)
user['surname'] = ldap_conn.get_user_sn(eachUser)
self.create_user(user, zabbix_grpid)
zabbix_all_users.append(eachUser)
print '>>> Updating user media for %s, adding email' % eachUser
mailaddress = ldap_conn.get_user_email(eachUser)
if mailaddress:
self.update_media(eachUser, mailaddress)
else:
# Update existing user to be member of the group
print '>>> Updating user %s, adding to group %s' % (eachUser, eachGroup)
self.update_user(eachUser, zabbix_grpid)
# Just mention any extra users in the groups, do not remove them
extra_users = set(zabbix_group_users) - set(ldap_users)
if extra_users:
print '>>> Users in group %s which are not found in LDAP group:' % eachGroup
for eachUser in extra_users:
print ' * %s' % eachUser
ldap_conn.disconnect()
class ZabbixLDAPConf(object):
"""
Zabbix-LDAP configuration class
Provides methods for parsing and retrieving config entries
"""
def __init__(self, config):
self.config = config
def load_config(self):
"""
Loads the configuration file
Raises:
ConfigParser.NoOptionError
"""
parser = ConfigParser.ConfigParser()
parser.read(self.config)
try:
self.ldap_uri = parser.get('ldap', 'uri')
self.ldap_base = parser.get('ldap', 'base')
self.ldap_groups = parser.get('ldap', 'groups').split(',')
self.ldap_type = parser.get('ldap', 'type')
self.ldap_user = parser.get('ldap', 'binduser')
self.ldap_pass = parser.get('ldap', 'bindpass')
self.zbx_server = parser.get('zabbix', 'server')
self.zbx_username = parser.get('zabbix', 'username')
self.zbx_password = parser.get('zabbix', 'password')
except ConfigParser.NoOptionError as e:
raise SystemExit, 'Configuration issues detected in %s' % self.config
def main():
usage="""
Usage: zabbix-ldap-sync -f <config>
zabbix-ldap-sync -v
zabbix-ldap-sync -h
Options:
-h, --help Display this usage info
-v, --version Display version and exit
-f <config>, --file <config> Configuration file to use
"""
args = docopt(usage, version="0.1.0")
config = ZabbixLDAPConf(args['--file'])
config.load_config()
# set up AD differences, if necessary
global active_directory
global group_filter
global group_member_attribute
global uid_attribute
global sn_filter
global givenname_filter
global mail_filter
if config.ldap_type == 'activedirectory':
active_directory = "true"
group_filter = "(&(objectClass=group)(name=%s))"
group_member_attribute = "member"
uid_attribute = "sAMAccountName"
sn_filter = "(&(objectClass=person)(sAMAccountName=%s))"
givenname_filter = "(&(objectClass=person)(sAMAccountName=%s))"
mail_filter = "(&(objectClass=person)(sAMAccountName=%s))"
else:
group_filter = "(&(objectClass=posixGroup)(cn=%s))"
group_member_attribute = "memberUid"
sn_filter = "(&(objectClass=posixAccount)(uid=%s))"
givenname_filter = "(&(objectClass=posixAccount)(uid=%s))"
mail_filter = "(&(objectClass=posixAccount)(uid=%s))"
zabbix_conn = ZabbixConn(config.zbx_server, config.zbx_username, config.zbx_password)
zabbix_conn.connect()
zabbix_conn.create_missing_groups(config.ldap_groups)
zabbix_conn.sync_users(config.ldap_uri, config.ldap_base, config.ldap_groups, config.ldap_user, config.ldap_pass)
if __name__ == '__main__':
main()