Hi, guys.

I'm working on a simple script that creates zimbra user accounts as I create them in my w2k AD server (via crontab). It also deletes zmibra accounts when no longer exist in my AD.

This is the first try (unstable, untested, unsecure) but wanted to share with you, maybe someone can help me to make it better.

The idea is simple: it makes a list of AD users via ldapsearch, then makes a list of ZCS users via zmprov and finally makes a diff between both to find different entries. Take a loot at it and tel me what do you think.

ToDo list:
- add an option to make it quiet to be run from crontab
- add an option to make it verbose so it can be debugged
- add an option to generate a log!

Code:
#!/bin/bash
# zsync_ad.sh is a script thant syncs AD users and Zimbra users
# It is unidirectional, just replicates changes from AD to ZCS
# Developed on by Eduardo Gonzalez <egrueda at gmail dot com> 
# Testing version 0.6 - Use at your own risk

LDAPSEARCH=/usr/bin/ldapsearch
ZMPROV=/opt/zimbra/bin/zmprov
DOMAIN_NAME="example.com"
TIMESTAMP=`date +%N`
TMP_DIR=/tmp
ADS_TMP=$TMP_DIR/users_ads_$TIMESTAMP.lst
ZCS_TMP=$TMP_DIR/users_zcs_$TIMESTAMP.lst
DIF_TMP=$TMP_DIR/users_dif_$TIMESTAMP.lst

# Server values
LDAP_SERVER="ldap://111.1.1.150"
BASEDN="dc=example,dc=com"
BINDDN="CN=username,DC=example,DC=com"
BINDPW="secret"
FILTER="(&(sAMAccountName=*)(objectClass=user)(givenName=*))"
FIELDS="mail"

# Extract users from ADS
echo -n "Quering ADS... "
$LDAPSEARCH -x -H $LDAP_SERVER -b $BASEDN -D "$BINDDN" -w $BINDPW "$FILTER" $FIELDS | \
  grep "@$DOMAIN_NAME" | \
  awk '{print $2}' | \
  sort > $ADS_TMP
echo "Found `cat $ADS_TMP | wc -l` users ($ADS_TMP)"

# Extract users from ZCS
echo -n "Quering ZCS... "
$ZMPROV gaa $DOMAIN_NAME > $ZCS_TMP
echo "Found `cat $ZCS_TMP | wc -l` users ($ZCS_TMP)"

# Generate diff
echo "Generating diff file ($DIF_TMP)"
diff -u $ZCS_TMP $ADS_TMP | grep "$DOMAIN_NAME" > $DIF_TMP

# Clean up users list
rm -f $ADS_TMP $ZCS_TMP

# Import new users
echo -n "New users: "
cat $DIF_TMP | grep ^+ | wc -l
for i in $(cat $DIF_TMP | grep ^+ | sed s/^+//g);
do
  echo -n " - Adding $i ";
  $ZMPROV createAccount $i passwd > /dev/null;
  RES=$?
  if [ "$RES" == "0" ]; then echo "[Ok]"; else echo "[Err]"; fi
done

# Delete old users
echo -n "Old users: "
cat $DIF_TMP | grep ^- | wc -l
for i in $(cat $DIF_TMP | grep ^- | sed s/^-//g);
do
  echo -n " - Deleting $i ";
  $ZMPROV deleteAccount $i > /dev/null;
  RES=$?
  if [ "$RES" == "0" ]; then echo "[Ok]"; else echo "[Err]"; fi
done


# Clean up diff list
rm -f $DIF_TMP
Cheers