Automate User Management on Linux with a Bash Script
Managing users on a Linux system can be a tedious task, especially when dealing with multiple users and groups. Automation can greatly simplify this process. In this article, we'll walk through creating a bash script to automate user creation, group assignment, and password management, logging all actions for auditing purposes.
Overview
Our script, create_users.sh
, will:
- Read a text file containing usernames and group names.
- Create users and assign them to specified groups.
- Ensure each user has a personal group.
- Set up home directories with appropriate permissions.
- Generate random passwords for users.
- Log all actions to
/var/log/user_management.log
. - Securely store generated passwords in
/var/secure/user_passwords.csv
.
Prerequisites
To follow along, you need:
- A Linux system with sudo privileges.
-
openssl
installed for generating random passwords.
Step-by-Step Guide
1. Prepare the User and Group Text File
First, create a text file that contains the usernames and group names. Each line should follow the format username; groups
, where groups are separated by commas.
Example user_groups.txt
:
alice; sudo,developers,web
bob; admin,devops
charlie; www-data
dave; sudo
eve; dev,admin,www-data
2. Write the Bash Script
Let's break down the script into major steps for clarity.
Step 1: Setting Up Logging and Password Storage
We start by defining the log file and password file locations and ensuring they exist with the appropriate permissions.
#!/bin/bash
# Log file location
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"
# Ensure the log file exists
touch $LOG_FILE
chmod 600 $LOG_FILE
# Ensure the password file exists and set appropriate permissions
mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
Step 2: Helper Functions
Next, we define a function to generate random passwords and another to log messages.
# Function to generate random passwords
generate_password() {
openssl rand -base64 12
}
# Log a message
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}
Step 3: Reading the Input File
We read the input file line by line and process each user and their groups.
# Check if the script is run with an argument
if [ $# -eq 0 ]; then
echo "Usage: $0 <name-of-text-file>"
exit 1
fi
# Read the file line by line
while IFS=';' read -r username groups; do
# Remove leading/trailing whitespace from username and groups
username=$(echo $username | xargs)
groups=$(echo $groups | xargs)
Step 4: Creating Users and Groups
We create users, assign them to their personal groups, and handle group assignments.
# Check if user already exists
if id -u $username >/dev/null 2>&1; then
log "User $username already exists. Skipping creation."
continue
fi
# Create user with a personal group
useradd -m -s /bin/bash $username
log "User $username created."
# Set up home directory permissions
chmod 700 /home/$username
chown $username:$username /home/$username
log "Set up home directory for $username."
# Generate random password and set it
password=$(generate_password)
echo "$username:$password" | chpasswd
echo "$username,$password" >> $PASSWORD_FILE
log "Password set for $username."
# Add user to their own group
usermod -aG $username $username
log "User $username added to their personal group $username."
Step 5: Assigning Users to Additional Groups
We ensure users are added to any additional groups specified in the text file.
# Assign user to additional groups
if [ -n "$groups" ]; then
IFS=',' read -r -a group_array <<< "$groups"
for group in "${group_array[@]}"; do
# Remove whitespace from group name
group=$(echo $group | xargs)
# Create group if it doesn't exist
if ! getent group $group >/dev/null; then
groupadd $group
log "Group $group created."
fi
# Add user to group
usermod -aG $group $username
log "User $username added to group $group."
done
fi
done < "$1"
Step 6: Final Steps
Finally, we ensure the password file is only readable by the owner.
# Ensure password file is only readable by the owner
chmod 600 $PASSWORD_FILE
echo "User creation process completed. Check $LOG_FILE for details."
3. Make the Script Executable
Ensure the script is executable by running:
chmod +x create_users.sh
4. Run the Script
Run the script with your user and group file as an argument:
sudo bash create_users.sh user_groups.txt
5. Verify the Results
-
Log file: Check
/var/log/user_management.log
for the log of all actions performed.
sudo cat /var/log/user_management.log
-
Password file: Check
/var/secure/user_passwords.csv
to view the usernames and their generated passwords (only accessible by the root user).
sudo cat /var/secure/user_passwords.csv
6. Deleting Users
To delete a user along with their home directory and mail spool, use:
sudo userdel -r username
Replace username
with the actual username you want to delete.
Conclusion
This script automates the tedious task of user management on a Linux system, ensuring users are created with the correct groups and home directory permissions, and passwords are securely managed. By logging actions and securely storing passwords, it also helps in maintaining a good audit trail and security practices. Automation like this can save valuable time and reduce the risk of manual errors, especially in larger environments.
Feel free to adapt this script to suit your specific requirements and extend its functionality as needed. Happy scripting!
Get more insight on scripting from the HNG internship - https://hng.tech/internship https://hng.tech/hire
Top comments (0)