Bulk adduser script
From Fratm.com
Our Exchange server at work crashed, and we needed a way to still let our users have e-mail, so one of the admins asked me if they created a list from the active directory server, if I could write a script that would bulk add all the users and set a temporary password for them. etc..etc..etc.
I said sure thing.. so here is what I did..
NOTE: This works on RedHat Enterprise Linux.. you may need to adjust the adduser parts to make it work with your flavor of linux.
First off, this is what the data from the AD server looked like.
dn: CN=John Doe,CN=Users,DC=ad,DC=ourdomain,DC=com name: John Doe dn: CN=Jane Doe Managers,CN=Users,DC=ad,DC=ourdomain,DC=com name: Jane Doe (repeat for 2000 entries..)
So I wrote this perl script to parse out the data, and create the accounts.
#!/usr/bin/perl
my $filename = shift;
if (!$filename) { $filename ="./ldaplist.ldif"; }
# Let's buffer the current passwd file..
open (PASS,"/etc/passwd") || die ("Unable to read password file..\n\n");
while (<PASS>)
{
($ulog,$null) = split(":",$_);
$PASS{$ulog} = $ulog;
}
close (PASS);
# Now lets open the AD list, and do our magic.
open (FILE,$filename) || die ("System failure!! Unable to open $filename \n");
while (<FILE>)
{
if (/^dn/) {
($name,$null) = split (",",$_);
$name =~ s/dn: CN=//ig;
($last,$first) = split (" ",$name);
$login = substr($first,0,1) . $last ;
$login =~ tr/A-Z/a-z/;
}
if (/^\n/) {
#print "$name:$last $first:$login\n";
if (!$PASS{$login}) {
print "Adding account for $last $first as $login\n";
system "useradd -d /home/staff2/$login -p TempPasswd -l $login \n";
system "chfn -f \"$last $first\" -o \"Staff Temp Account\" $login \n";
$PASS{$login} = $login;
} else { print "Skipping $last $first : $login \n"; }
}
}
close (FILE);
This script is real simple, first it buffers the /etc/passwd entries into a hash, next it opens up the data file with the accounts to be added in it, and parses out the first name and last name, builds a login name (first initial + last name), then it looks to see if there is a hash entry for that new login name in the passwd buffer hash. If it finds an existing entry it skips this user, if it does not find an entry it does the appropriate system calls to create a user, and then set their finger information, and lastly ads them to the buffer hash (just to be safe). Oh also when it creates the login name, it converts it to all lower case.
Lucky, we got our exchange server online, and I did not have to use this script, so at this point it is untested, so if you need to use something like this, you can use it but at your OWN RISK.. (In other words I ain't responsible if it screws up!!!)
-Fratm
