Nothing To Lose

If you don’t have it, how can you lose it!
Subscribe

Adding Multiple Users With Random Password in Linux

March 19, 2011 By: Dexter Category: BASH, Linux, Linux Commands, Shell Scripting

Some or the other time you will come across a need to add multiple users to your Linux system, if it is 5 to 10 its ok, but what if you need to add a list of 100 or 200 users at a time.

What you need is a text file containing your username (Login ID) and random password separated by , (comma) stored in a file. I am calling this file uidpass.csv.

Loginid,Password
2001,k8jr9yic
2002,agiidmcc
2003,mp9cxmzj
2004,e3mjyxcb
2005,vlsvc3yc
2006,a9kelmhy
……………..
……………
2299,54wgh67b

Save this file as whatever name you want. Now what we need a is command to add users to the system. The useradd command in Linux lets you do that, intrestingly it also allows you to add the password with the option -p at the same time no need to use the passwd command. The only problem with the -p option is that it need the password to be provided in encrypted format.
Here the utility mkpasswd comes in handy. The mkpasswd command can take a string can return encrypted value for it that is required by the password option of useradd.

Here is the script which will read the file containing the userid,password

#!/bin/bash
for lines in `cat uidpass.csv`
do
userid=`echo $lines |cut -d’,’ -f1`
userpw=`echo $lines |cut -d’,’ -f2`
useradd -mc”New User $userid” -s /bin/bash  -p `mkpasswd $userpw`  $userid
done

So whats happening here lets see line by line

for lines in `cat uidpass.csv`
start the for loop read every line in uidpass.csv and put ever line one by one in lines variable for every iteration.

userid=`echo $lines |cut -d’,’ -f1`

cut the line in variable lines on the delimiter comma and store first field in variable userid

userpw=`echo $lines |cut -d’,’ -f2`

cut the line in variable lines on the delimiter comma and store second field in variable userpw

useradd -mc”New User $userid” -s /bin/bash  -p `mkpasswd $userpw`  $userid

Run the user add command for the username in userid and password in userpw, in the line itself the mkpasswd will encrypt the userpw and then give it to the option password option.

The loop will run for all the lines in your file.

hope this helps.