Automating User Management in Linux with Bash Scripts
Source: Dev.to
🚀 The Goal
The objective was to create a system that can:
- Read a list of usernames from a text file.
- Bulk create users with a default password and force a password change on first login.
- Bulk delete users and their home directories.
- Log every action for auditing purposes.
🛠️ The Scripts
1. The User List (users.txt)
Add one username per line:
dev1
dev2
ronald
2. User Creation (create_users.sh)
This script handles onboarding. It checks if a user exists, creates them if they don’t, sets a temporary password, and expires it immediately to ensure security.
#!/bin/bash
USER_FILE="users.txt"
PASSWORD="DevOps@1234!"
LOG_FILE="user_creation.log"
echo "User Creation Started: $(date)" >> "$LOG_FILE"
while read USERNAME; do
if id "$USERNAME" &>/dev/null; then
echo "User $USERNAME already exists" | tee -a "$LOG_FILE"
else
sudo useradd -m "$USERNAME"
echo "$USERNAME:$PASSWORD" | sudo chpasswd
sudo passwd -e "$USERNAME"
echo "User $USERNAME created successfully" | tee -a "$LOG_FILE"
fi
done > "$LOG_FILE"
Key Features
useradd -m: Creates the home directory automatically.chpasswd: Efficiently sets passwords from a string.passwd -e: Forces the user to change their password at the first login—a crucial security step.
3. User Deletion (del_user.sh)
When it’s time to offboard, this script makes it a one‑command job.
#!/bin/bash
USER_LIST="users.txt"
LOG_FILE="user_deletion.log"
echo "User Deletion Started: $(date)" >> "$LOG_FILE"
while read USERNAME; do
if id "$USERNAME" &>/dev/null; then
sudo userdel -r "$USERNAME"
echo "User $USERNAME Deleted Successfully" | tee -a "$LOG_FILE"
else
echo "User $USERNAME does not exist" | tee -a "$LOG_FILE"
fi
done > "$LOG_FILE"
Key Features
userdel -r: Removes the user and their home directory, keeping the system clean.- Error handling: Checks if the user exists before attempting deletion.
📈 Logging for Auditing
Both scripts generate log files (user_creation.log and user_deletion.log). This is essential for tracking who was created or removed and when, satisfying typical production‑environment audit requirements.
💡 How to Use It
-
Clone the repository.
-
Populate
users.txtwith the desired usernames. -
Make the scripts executable:
chmod +x *.sh -
Run
./create_users.shto onboard or./del_user.shto offboard.
🔒 Security Note
For demonstration purposes the password is hard‑coded. In a real‑world scenario consider:
- Storing the default password in an environment variable.
- Using a secret‑management tool.
- Prompting for a password during script execution.
🏁 Conclusion
Bash scripting is a superpower for any Linux user. With just a few lines of code, a tedious manual process becomes a reliable, logged, and automated workflow.
Check out the full project on my GitHub.