Bash Script (with Perl) to Bulk useradd to server

879

The script below will read through file usersfile.txt and then add users to a linux system with perl installed on it.

the script reads line by line through usersfile.txt which is space separated like so

User1 passwd1 group1

User2 passwd2 groupx, and so on.

You need to supply passwords in plaintext in this file, so I only suggest keeping the file on a server for the duration of the script run.

The plaintext password then uses the perl crypt library alongside the standard useradd script.

 

#!/bin/bash
if [ $(id -u) -eq 0 ]; then
NEW_USERS=”/usersfile.txt”
HOME_BASE=”/home/”
cat ${NEW_USERS} |
while read USER PASSWORD GROUP
do
pass=$(perl -e ‘print crypt($ARGV[0], “password”)’ $PASSWORD)
egrep “^$USER[0]” /etc/passwd > /dev/null
if [ $? -eq 0 ]; then
echo “User $USER exists!”
exit 1
else
useradd -g ${GROUP} -p ${pass} -m -d ${HOME_BASE}${USER} ${USER}
[ $? -eq 0 ] && echo “User $USER has been added to the system” || echo “Failed adding user $USER!”
fi
done
fi