Managing users on a Linux system can be a time-consuming task, especially in environments where users frequently join or leave. Automating this process can save administrators a lot of time and reduce human error. In this article, we'll walk through a Bash script designed to automate the creation of Linux users and their respective groups. This script ensures security, logging, and proper group management.
Why Automate User Management?
Automation helps maintain consistency and efficiency in repetitive tasks. In large organizations or during internships, like those offered by the HNG Internship, managing multiple users can quickly become a complex and error-prone process. A well-designed script can streamline this process, making it easier to manage users securely and effectively.
Prerequisites
Before diving into the script, ensure you have the following:
- A Linux operating system (tested on Ubuntu).
- Bash shell (
/bin/bash
). - OpenSSL for password generation (
openssl
). - Root privileges (
sudo
).
The source code can be found on my GitHub repo
The Bash Script
Here's the full script:
#!/bin/bash
# Check if the input file exists
if [ ! -f "$1" ]; then
echo "Error: Input file not found."
exit 1
fi
# Ensure log and secure directories are initialized once
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"
# Initialize log file
if [ ! -f "$LOG_FILE" ]; then
sudo touch "$LOG_FILE"
sudo chown root:root "$LOG_FILE"
fi
# Initialize password file
if [ ! -f "$PASSWORD_FILE" ]; then
sudo mkdir -p /var/secure
sudo touch "$PASSWORD_FILE"
sudo chown root:root "$PASSWORD_FILE"
sudo chmod 600 "$PASSWORD_FILE"
fi
# Redirect stdout and stderr to the log file
exec > >(sudo tee -a "$LOG_FILE") 2>&1
# Function to check if user exists
user_exists() {
id "$1" &>/dev/null
}
# Function to check if a group exists
group_exists() {
getent group "$1" > /dev/null 2>&1
}
# Function to check if a user is in a group
user_in_group() {
id -nG "$1" | grep -qw "$2"
}
# Read each line from the input file
while IFS=';' read -r username groups; do
# Trim whitespace
username=$(echo "$username" | tr -d '[:space:]')
groups=$(echo "$groups" | tr -d '[:space:]')
# Check if the user already exists
if user_exists "$username"; then
echo "User $username already exists."
else
# Create user
sudo useradd -m "$username"
# Generate random password
password=$(openssl rand -base64 12)
# Set password for user
echo "$username:$password" | sudo chpasswd
# Log actions
echo "User $username created. Password: $password"
# Store passwords securely
echo "$username,$password" | sudo tee -a "$PASSWORD_FILE"
fi
# Ensure the user's home directory and personal group exist
sudo mkdir -p "/home/$username"
sudo chown "$username:$username" "/home/$username"
# Split the groups string into an array
IFS=',' read -ra group_array <<< "$groups"
# Check each group
for group in "${group_array[@]}"; do
if group_exists "$group"; then
echo "Group $group exists."
else
echo "Group $group does not exist. Creating group $group."
sudo groupadd "$group"
fi
if user_in_group "$username" "$group"; then
echo "User $username is already in group $group."
else
echo "Adding user $username to group $group."
sudo usermod -aG "$group" "$username"
fi
done
done < "$1"
How the Script Works
- Input File Verification: The script starts by checking if the input file exists. If not, it exits with an error message.
- Log and Secure Directory Initialization: The script sets up a log file to keep track of its actions and a secure password file to store user passwords. These files are created with proper permissions to ensure security.
-
User and Group Management:
- The script reads each line from the input file, which contains usernames and their associated groups.
- It checks if each user already exists. If not, it creates the user and assigns a randomly generated password.
- It ensures the user's home directory and personal group are set up.
- The script then processes each group, checking if it exists and creating it if necessary, before adding the user to the group.
Usage
- Save the user information in a file, e.g.,
usersname.txt
, formatted asusername;group1,group2,group3
. - Run the script with the user information file as an argument:
./user_creation_script.sh usersname.txt
Benefits of This Script
- Automation: Reduces the manual effort required to manage users and groups.
- Security: Ensures passwords are stored securely and logs all actions for auditing purposes.
- Consistency: Maintains a consistent approach to user and group management.
Conclusion
Automating user management on Linux systems can significantly enhance efficiency and security. This script provides a robust solution for creating users and managing their groups. For those interested in more automation and development practices, the HNG Internship offers a great opportunity to learn and grow in a collaborative environment.
By leveraging such scripts, administrators can focus on more critical tasks, knowing that user management is handled consistently and securely.
For more information on hiring talents trained in such automation practices, visit HNG Hire.
Feel free to share your thoughts or improvements on this script in the comments!
Happy coding! Written by: Candy-DevOps
Top comments (0)