The following extends the original code as follows:
It specifies a(n additional) group to add users to.
That group:
- can be an existing group that is assumed to already be
sudo
-enabled, such as the sudo
group on Ubuntu.
- If it doesn't exist, it is created, and
sudo
-enabled via a dedicated file in directory /etc/sudoers.d/
named for the group - see the code and man sudoers
for details.
In the user-creation loop, each newly created user is added to that group with usermod
:
sudo usermod <user> -G <group>
- Note: You should also be able to do this as part of the
useradd
call.
This should sudo
-enable all newly created users.
Note:
- Providing passwords via plain-text files is a security risk.
- For an explanation of the techniques used in the user-creation (
while
) loop, see this answer.
#!/usr/bin/env bash
# The sudo-enabled user group to add users to.
# Either choose a preexisting one, such as 'sudo' on Ubuntu, or
# specify a new group to create and sudo-enable on demand (see below).
sudoEnabledGroup='foosudo'
# Test if the group exists.
[[ -z $(awk -F: -v g=$sudoEnabledGroup '$1==g' /etc/group) ]] && groupExists=0 || groupExists=1
# If the group doesn't exist yet, create it on demand and sudo-enable it.
# Note: Deactive this `if` statement, if the group must already exist.
if (( ! groupExists )); then
printf "Creating group: %s...\n" $sudoEnabledGroup
# Create the group.
sudo groupadd $sudoEnabledGroup || exit
# Sudo-enable it, via a dedicated file in directory /etc/sudoers.d/, named for the group.
# CAUTION: The following enables the MOST PRIVILEGES POSSIBLE for the given
# group. See `man sudoers`, section "SUDOERS FILE FORMAT" for details.
customSudoerFile=/etc/sudoers.d/$sudoEnabledGroup
printf "... and sudo-enabling it via file $customSudoerFile.\n" $sudoEnabledGroup
sudo sh -c "echo '%$sudoEnabledGroup ALL=(ALL:ALL) ALL' >$customSudoerFile"
fi
# Loop over the user names and passwords from the input files.
usersFile="users.txt"
# CAVEAT: Providing passwords via plain-text file is a SECURITY RISK.
passwdFile="passwords.txt"
printf "Creating users from files '%s' and '%s' and assigning them to group '%s'...\n" "$usersFile" "$passwdFile" $sudoEnabledGroup
while read user passwd; do
printf " Creating user: %s...\n" $user
# Create the user.
sudo useradd -m -s /bin/bash $user || exit
# Add it to the the sudo-enabled group designated above.
sudo usermod $user -G $sudoEnabledGroup || exit
# Assign the password to the user.
# Password is passed via stdin, *twice* (for confirmation).
# This will print something like the following:
# "Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully"
# You can suppress with 2>/dev/null, but that would also mask true errors.
sudo passwd $user <<< "$passwd"$'\n'"$passwd" || exit
done < <(paste "$usersFile" "$passwdFile")
printf 'Done.\n'