This content originally appeared on DEV Community and was authored by Celestina
Hey there! Ever wondered how tech teams smoothly integrate new members into their systems? Scripting has become the unsung hero! Imagine effortlessly setting up user accounts, creating personalized groups, and ensuring security—all with a few lines of code. In this article, we'll explore how automation through scripting not only simplifies complex tasks but also minimizes errors and maximizes efficiency.
In this article, we will be creating a Bash script that helps create users and groups on the fly. This is part of a task assigned during the HNG Internship. The internship also provides a premium service at a stipend, exposing you to many more opportunities.
Anyways, let's get to the party.
Tools needed:
- Unix (Linux, macOS, WSL)
- Editor (Vim, Vi, Nano, VSCode). I will be using Vim as the editor of choice; here is a link to learn more about Vim.
Scripting
First, create a file that will contain the script using touch create_users.sh
. You can also create and open the file simultaneously using Vim.
touch create_users.sh
vim create_users.sh
At the start of the script, we need to ensure that only privileged users with root privileges can execute the script.
#!/bin/bash
# Check if running as root
if [[ $UID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
The script checks if the user and group file exists. This is important for error handling and preventing repetition.
# Check if the file with users and their corresponding groups exists
if [[ $# -ne 1 ]]; then
echo "Use: $0 <user_file>"
exit 1
fi
USER_FILE=$1
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
# Create the log and password files if they do not exist
touch $LOG_FILE
mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
Next, we define a function to log activities into the log file.
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') $1" >> $LOG_FILE
}
We create a function to handle user creation. This function will also manage group assignments and password generation.
# Function to create a user
create_user() {
local user=$1 # Username passed as parameter
local groups=$2 # Groups passed as parameter
local password # Variable to store generated password
# Check if user already exists
if id "$user" &>/dev/null; then
echo "User $user already exists" | tee -a $LOG_FILE
return 1
fi
# Create user's personal group if it doesn't exist
if ! grep -q "^$user:" /etc/group; then
groupadd "$user"
log "Created group: $user"
fi
# Check and create required groups if they don't exist
IFS=',' read -ra group_list <<< "$groups"
for group in "${group_list[@]}"; do
if ! grep -q "^$group:" /etc/group; then
groupadd "$group"
log "Created group: $group"
fi
done
# Create the user with specified groups and assign a home directory
useradd -m -s /bin/bash -g "$user" -G "$groups" "$user" 2>>$LOG_FILE
# Check if user creation was successful
if [ $? -ne 0 ]; then
echo "Failed to create user $user" | tee -a $LOG_FILE
return 1
fi
# Generate a random password for the user
password=$(openssl rand -base64 15)
# Set user's password using chpasswd command
echo "$user:$password" | chpasswd
if [ $? -ne 0 ]; then
echo "Failed to set password for user $user" | tee -a $LOG_FILE
return 1
fi
# Store the password securely in the password file
echo "$user:$password" >> $PASSWORD_FILE
# Log user creation with assigned groups
echo "Created user $user with groups $groups" | tee -a $LOG_FILE
# Set permissions for the user's home directory
if [ ! -d "/home/$user" ]; then
mkdir -p "/home/$user"
chown -R "$user:$user" "/home/$user"
chmod 700 "/home/$user"
log "Created home directory for $user"
fi
}
Next, the script reads the user file and processes each entry to create the users.
# Main script logic
while IFS=';' read -r username groups; do
username=$(echo $username | tr -d '[:space:]') # Trim whitespace from username
groups=$(echo $groups | tr -d '[:space:]') # Trim whitespace from groups
create_user "$username" "$groups" # Call create_user function for each username and groups pair
done < "$USER_FILE"
Testing
Make the script executable:
chmod +x create_users.sh
Now, to test the script, create a simple CSV file:
vim user_data.csv
Add the following content to user_data.csv
:
light;sudo,dev,www-data
idimma;sudo
mayowa;dev,www-data
emeka;admin,dev
sarah;www-data
john;admin,sudo,dev
Check the log file to get the output:
sudo cat /var/log/user_management.log
And check the password file to see the generated passwords:
sudo cat /var/secure/user_passwords.txt
This content originally appeared on DEV Community and was authored by Celestina

Celestina | Sciencx (2024-07-02T22:53:48+00:00) User and groups creation automation in linux. Retrieved from https://www.scien.cx/2024/07/02/user-and-groups-creation-automation-in-linux/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.