#!/usr/bin/env python # -*- coding: utf-8 -*- # Requires Python 3.6+ import zulip import ldap # setup a function to correctly extract attribute values from the ldap results: def getAttribute(data, aName): if aName in data[0][1]: v = data[0][1][aName][0].decode('utf-8', 'ignore') return v return "" # Pass the path to your zuliprc file here. (must be an organization admin credential/apikey # to create users, even bots with super knight-ed access can't create users) client = zulip.Client(config_file="~/zuliprc") # Get all users in the zulip realm allmembers = client.get_members() # extract just the 'members' list from the results: goodmembers = allmembers['members'] # create the comparison list: zuliplist = [] # for each loop through the goodmembers list of dictionary user entries and store in the zuliplist for d in goodmembers: # add each discovered email address to the zulip list: zuliplist.append(d['email']) # turn the list into a set: zulipset = set(zuliplist) # LDAP endpoint connection: LDAP_URL = "ldaps://ds01.avroid.tech" LDAP_USER = "uid=svc_ipa,cn=users,cn=accounts,dc=avroid,dc=tech" LDAP_PASSWORD = "xxxxxxxxxxxxx" LDAP_BASEDN = "cn=users,cn=accounts,dc=avroid,dc=tech" LDAP_SEARCH_FILTER = "(&(objectClass=inetorgperson)(memberOf=cn=org-avroid-all,cn=groups,cn=accounts,dc=avroid,dc=tech))" LDAP_RETRIEVE_ATTRIBUTES = ["krbPrincipalName", "uid", "DisplayName"] # Define the LDAP lookup using parameters from above l = ldap.initialize(LDAP_URL) l.simple_bind_s(LDAP_USER, LDAP_PASSWORD) searchScope = ldap.SCOPE_SUBTREE # initialize i to zero to use it as a counter i = 0 # harvest the ldap results and check the list against the zulipset, create the user in zulip if missing: try: ldap_result_id = l.search(LDAP_BASEDN, searchScope, LDAP_SEARCH_FILTER, LDAP_RETRIEVE_ATTRIBUTES) result_set = [] while 1: i = i + 1 result_type, result_data = l.result(ldap_result_id, 0) if not result_data: break else: upn = getAttribute(result_data,"krbPrincipalName") # Email | krbPrincipalName shortname = getAttribute(result_data,"uid") # UID displayname = getAttribute(result_data,"DisplayName") # DisplayName if upn in zulipset: print("user found in zulip already : "+upn) else: print("user needs to be added to zulip : "+upn) # Create the user with a 'fake' password via the zulip library # (the password field is required, but only SAMLauth backend is enabled, so this password "can't" be used) request = { 'email': upn, 'password': 'fakeComplexpasswordThatWillNeverbeused!4858025279014', 'full_name': displayname, 'short_name': shortname } result = client.create_user(request) print(result) # print any ldap errors that may have occurred during the query: except ldap.LDAPError as e: print(e)