Skip to content

Instantly share code, notes, and snippets.

@peacepenguin
Created October 16, 2019 17:07
Show Gist options
  • Save peacepenguin/45ed1cd5ab32f7dadd03dcfbd1b5c857 to your computer and use it in GitHub Desktop.
Save peacepenguin/45ed1cd5ab32f7dadd03dcfbd1b5c857 to your computer and use it in GitHub Desktop.
#!/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_URL = "ldaps://ad01.example.net"
LDAP_USER = "CN=ldapread,OU=ServiceAccounts,DC=example,DC=net"
LDAP_PASSWORD = "ldapreadaccountpassword382809248024"
LDAP_BASEDN = "OU=Corporate,DC=example,DC=net"
LDAP_SEARCH_FILTER = "(objectClass=user)"
LDAP_RETRIEVE_ATTRIBUTES = ["userPrincipalName","sAMAccountName","name"]
# 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 (result_data == []):
break
else:
upn = getAttribute(result_data,"userPrincipalName")
shortname = getAttribute(result_data,"sAMAccountName")
displayname = getAttribute(result_data,"name")
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment