Created
April 5, 2020 22:08
-
-
Save Cyxo/1ee6f1f8643d3ffbfe5912ad16f90272 to your computer and use it in GitHub Desktop.
Creates Zimbra account for each account in an LDAP directory (run as root on the Zimbra server, or put in the crontab)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import subprocess as sp | |
from time import sleep | |
import re | |
# Change these parameters for your own configuration | |
LDAP_URL="ldap://ldap.internal.example.com:389" | |
BASE_DN="ou=people,dc=example,dc=com" | |
FILTER="(objectClass=inetOrgPerson)" # This is a filter to get only people, change for your own case | |
ATTR=["uid", "givenName", "sn"] | |
DOMAIN = "example.com" | |
NAME_ALIAS=True # Whether to create first_name.last_name@domain as an alias to ldap_id@domain | |
# Get a list of existing Zimbra accounts | |
p = sp.Popen("su - zimbra -c 'echo gaa | zmprov -l'", stdout=sp.PIPE, shell=True) | |
(accounts,_) = p.communicate() | |
p.wait() | |
accounts = accounts.decode().splitlines() | |
acc = [] | |
for a in accounts: | |
print(a) | |
if "@" in a: | |
acc.append(a) | |
# Get a list of accounts on the LDAP directory | |
ldapacc = {} | |
p = sp.Popen("ldapsearch -H %s -x -b %s '%s' %s" % (LDAP_URL, BASE_DN, FILTER, " ".join(ATTR)), stdout=sp.PIPE, shell=True) | |
(l,_) = p.communicate() | |
p.wait() | |
l = l.decode().splitlines() | |
lastcn = "" | |
for line in l: | |
a = re.search(r'(\w+):', line) | |
if a: | |
attribute = a.group(1) | |
else: | |
continue | |
if attribute == "dn": | |
cn = re.search(r'cn=(.*),'+BASE_DN, line).group(1) | |
ldapacc[cn] = {} | |
lastcn = cn | |
elif attribute in ATTR: | |
ldapacc[lastcn][attribute] = line[len(attribute)+2:] | |
# Makes a list of commands to create the new accounts | |
toadd = [] | |
for i in ldapacc.keys(): | |
if i + "@" + DOMAIN not in acc: | |
print("Adding", i) | |
pwd = "".join([random.choice('azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890') for _ in range(16)]) | |
toadd.append("ca %s@%s %s displayName %s\n" % (i,DOMAIN,pwd,i)) | |
if NAME_ALIAS: | |
toadd.append("aaa %s@%s %s.%s@%s\n" % (i,DOMAIN,ldapacc[i]["givenName"].lower(),ldapacc[i]["sn"].lower(),DOMAIN)) | |
toadd.append("exit\n") | |
with open("toadd.txt", "w+") as f: | |
f.writelines(toadd) | |
# Create the new accounts | |
p = sp.Popen("cat toadd.txt | su - zimbra -c zmprov", shell=True) | |
p.wait() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment