#!/usr/bin/python import sys import ldap import subprocess LDAP_URI = 'ldap://db.cluster.univ.kiev.ua:389/' LDAP_BASEDN = 'ou=People,dc=cluster,dc=univ,dc=kiev,dc=ua' MAILMAN_BIN_PATH = '/usr/lib/mailman/bin/' MAILMAN_LIST = 'knu-hpc-users' def get_ldap_emails (): try: ldap_conn = ldap.initialize(LDAP_URI) ldap_conn.protocol_version = ldap.VERSION3 ldap_list = ldap_conn.search_st(LDAP_BASEDN, ldap.SCOPE_SUBTREE, attrlist=['mail'], timeout=10) ldap_emails = [] for (dn, attrs_list) in ldap_list: if 'mail' in attrs_list: ldap_emails.extend(attrs_list['mail']) ldap_conn.unbind() return [ email.lower() for email in ldap_emails ] except ldap.LDAPError as e: print e sys.exit(1) def get_mailman_emails (): try: output = subprocess.check_output([MAILMAN_BIN_PATH + 'list_members', MAILMAN_LIST]) return output.split() except subprocess.CalledProcessError as e: print e sys.exit(1) def mailman_user_add (email): cmd = MAILMAN_BIN_PATH + 'add_members -w n -a n -r - ' + MAILMAN_LIST proc = subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE) proc.communicate(email) def mailman_user_del (email): cmd = MAILMAN_BIN_PATH + 'remove_members -n -N -f - ' + MAILMAN_LIST proc = subprocess.Popen(cmd,shell=True,stdin=subprocess.PIPE) proc.communicate(email) if not proc.returncode: print 'Unsubscribed: ' + email else: print 'Failed to unsubscribe: ' + email def main(): ldap_emails = get_ldap_emails() if not ldap_emails: print 'LDAP bind is successfull, but query returns no e-mails.' print 'Skipping mailman database manipulation.' sys.exit(0) mailman_emails = get_mailman_emails() for email in ldap_emails: if email in mailman_emails: mailman_emails.remove(email) continue else: mailman_user_add(email) for email in mailman_emails: mailman_user_del(email) main()