Last active
June 19, 2016 08:08
-
-
Save tfohlmeister/806986393b19c6d43a5475d9b61c4cd2 to your computer and use it in GitHub Desktop.
This python script takes a list of users (email adresses, in this case taken from a Zimbra user base) and compares them to the LDAPUsers table of Seafile. New users are added automatically, missing users are disabled. Update `seafile_pw` to match your connection and run this script as often as necessary. LDAP syncing users is usually a Seafile P…
This file contains 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
#!/usr/bin/env python2 | |
import MySQLdb | |
import sys | |
from subprocess import Popen, PIPE | |
def sqlexec(arg, *args): | |
cur = db.cursor(); | |
try: | |
cur.execute(arg % args) | |
except Exception as e: | |
print "Error %s" % e | |
except MySQLdb.Error, e: | |
try: | |
print "MySQL Error [%d]: %s" % (e.args[0], e.args[1]) | |
except IndexError: | |
print "MySQL Error: %s" % str(e) | |
return cur | |
users = [] | |
db = MySQLdb.connect(host="localhost", user="seafile", passwd="seafile_pw", db="ccnet-db") | |
# get active users from Zimbra | |
# stores mail adresses in list users | |
# update to match your setup (e.g. if not using Zimbra) | |
p = Popen(["zmprov", "sa", "&(objectClass=zimbraAccount)(!(objectClass=zimbraDistributionList))(!(zimbraHideInGal=TRUE))"], stdout=PIPE, bufsize=1) | |
with p.stdout: | |
for line in iter(p.stdout.readline, b''): | |
mail = line.replace('\n', '') | |
users.append(mail) | |
#print "Found %s" % mail | |
p.wait() # wait for the subprocess to exit | |
# go through all users and disable those who were not on the list (this disables access for deleted accounts) | |
cur = sqlexec("SELECT `id`, `email`, `is_active` FROM LDAPUsers") | |
for row in cur.fetchall(): | |
id=row[0] | |
mail=row[1] | |
active=row[2] | |
if mail in users: # if this this user is still on the list we skip him or her | |
if active==0: # user not activated, activate | |
sqlexec("UPDATE LDAPUsers SET `is_active`=1 WHERE `id`=%s",id).close() | |
print "Enabled %s" % mail | |
else: | |
print "Nothing to do %s" % mail | |
# remove from list and break to next item | |
users.remove(mail) | |
continue | |
# if we arrive here it means the user should no longer be active in seafile | |
if active==1: # only update row if user is still active | |
sqlexec("UPDATE LDAPUsers SET `is_active`=0 WHERE `id`=%s",id).close() | |
print "Disabled %s" % mail | |
cur.close() | |
# every user still on users list need to be added to DB | |
for user in users: | |
sqlexec("INSERT INTO LDAPUsers (email, password, is_staff, is_active) VALUES ('%s','',0,1)", user).close() | |
print "Added %s" % user | |
db.commit() | |
db.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment