We are running dovecot as MDA. Dovecot gets its user details from OpenLDAP and adds new users automatically. But removing a user in LDAP does not mean it gets removed in Dovecot as well. To have this a little bit more comfortable, I created this little script here:
#!/bin/bash
MAILDIR="/mails"
LDAP_HOST="ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock"
LDAP_BIND_USER="cn=Manager,dc=example,dc=com"
LDAP_BIND_PASS="password"
LDAP_BASE_DN="ou=People,dc=example,dc=com"
for DOMAINDIR in $MAILDIR/*;do
if [ -d $DOMAINDIR ];then
DOMAIN=$(echo $DOMAINDIR | sed 's/\//\ /g' | awk '{print $4}')
for USERDIR in $DOMAINDIR/*;do
if [ -d $USERDIR ];then
USER=$(echo $USERDIR | sed 's/\//\ /g' | awk '{print $5}')
MAIL="$USER@$DOMAIN"
EXISTS=$(ldapsearch -H $LDAP_HOST -D $LDAP_BIND_USER \
-w $LDAP_BIND_PASS -x -b $LDAP_BASE_DN \
mail=$MAIL mail | grep -c dn\:)
if [ "$EXISTS" == "0" ];then
echo "$MAIL is obsolete."
echo -n "Removing userdir..."
rm -rf $USERDIR
echo " done."
fi
fi
done
fi
done
What the script does is to crawl every subdirectory of MAILDIR. This is where we receive the domain names through a sed/awk-combination. For every domain name we crawl its userbase. A similar sed/awk-combination is being used to receive the user names. Then we create an eMail address out of the two retrieved bits of information. Now we are ready to check this mail address against the LDAP. If we receive a negative answer (address is not found and therefore no “dn”), we can be sure the eMail account has been removed. Finally, we remove the mail directory of the non-existing user.
The script itself should be handed over to the cron, I’d say.
Here is the download for the lazy.