Some times there will be a requirement for adding multiple users on servers. Using adduser/useradd command we can not create multiple user accounts in one shot. We can write a shell script to do this. But there is no need to write a script for this. There is an inbuilt Linux command called newusers which is used to create multiple users in batch mode. We will see both in this post.

Scenario 1: I want to create 500 users at a time and users will start baci how can i do that with a shell script?

#!/bin/bash
#Author:Surendra Kumar Anne
#Purpose:To automate user creation
#Date/Time:06-08-2011.19:10
mkdir -p /home/admin/useraccounts

for (( i=0; i<=500; i++ )) 

do

#Create users whose name starts with baci, 

#so this script will create baci1, baci2, baci3 etc depending on i value.   

useradd baci$i

#this command is bit tricky, < /dev/urandom  

#will generate all the random characters which are not even present

#on keyboard.. and tr -dc A-Na-n1-9, will display only characters

#which are from A to N, a to n and 1 to 9. This is to avoide o(small o),  

#O(capital o), 0(numerical zero) characters in order to remove 

#confusion in the password.  #And there is no character limit.   so head -c8

#will limit the random characters to just 8

< /dev/urandom tr -dc A-Na-n1-9_ | head -c8 > /tmp/passwd.txt 

#As this is an automated shell script, the below command will take

#password from STDIN(--stdin) ie /tmp/passwd.txt  

cat /tmp/passwd.txt | passwd --stdin user$i  

echo -e "Username:baci$i" > /home/admin/useraccounts/baci$i 

 echo -e "password:" >> /home/admin/useraccounts/baci$i  

cat /tmp/passwd.txt >> /home/admin/useraccounts/baci$i  

done

rm -rf /tmp/passwd.txt

Scenario2: Through newusers command.

Step1: Create a file with user details as password file syntax

#vi /root/userlist.txt

In the file each line should contain as below mention  syntax
username:password:User ID:Group ID:Comments:Userhome directory:User shell

Example syntax:

alex:UV4Ziu6v:2001:2001:The user alex belongs to finance dept:/home/alex:/bin/bash

Like this create as many lines you want to create that many user that many lines you can create.

Step2:Use newusers command to create batch users at a time.

#newusers /root/userlist.txt

Check /etc/passwd and /etc/shadow files to check weather users are created or not.