As Rocael suggested, you should look at the IMS batch sync stuff in the authentication package. I haven't looked at the code but it does what you want you apparently are looking to do.
Where is your user data coming from? If from LDAP, I have a couple of scripts that can generate IMS XML suitable for the batch sync process. I'm doing this myself currently.