Table Of Content
- Introduction
- script overview
- Conclusion
Introduction
A Bash script is a text file containing a series of commands written in the Bash (Bourne Again SHell) scripting language, which is a command processor that typically runs in a text window where the user types commands to perform actions. A Bash script allows users to automate repetitive tasks, manage system operations, and perform complex operations by executing commands.
As a SysOps engineer, managing user accounts and groups is crucial for maintaining a secure and organized development environment. In this article, I will guide you through a bash script designed to automate user creation, assign groups, set up home directories, and handle permissions efficiently.
The script, create_users.sh, performs the following tasks:
- Reading Input: It reads a text file containing usernames and their associated groups.
User and Group Creation: It creates users and their groups if they do not already exist.
Home Directory Setup: It sets up home directories with appropriate permissions and ownership.
Password Generation: It generates random passwords for the users.
Logging: It logs all actions to /var/log/user_management.log and stores the passwords securely in /var/secure/user_passwords.csv.
Script Overview
Here’s a detailed breakdown of the script:
- Checking Input Argument: The script checks if the input file is provided as an argument.
if [ -z "$1" ]; then
echo "Usage: $0 <name-of-text-file>"
exit 1
fi
- Initialization: It initializes log and password files and ensures the secure directory exists.
# Function to generate a random password
generate_password() {
# using 'openssl rand -base64 12’ to generate a 12-character password
openssl rand -base64 12
}
# Read input file line by line
while IFS=';' read -r username groups; do
# Create groups if they don't exist
for group in $(echo "$groups" | tr ',' ' '); do
groupadd "$group" 2>/dev/null || echo "Group $group already exists"
done
create user
useradd -m "$username" -G "$groups" 2>/dev/null || echo "User $username already exists"
- command that sets passwords
password=$(generate_password)
echo "$username:$password" | chpasswd
- Command that logs actions
echo "$(date '+%Y-%m-%d %H:%M:%S') - Created user $username with groups: $groups" >> "$log_file"
- Command that stores password securely
echo "$username:$password" >> "$password_file"
done < "$input_file"
Conclusion
This script simplifies managing users and groups on a Linux system, ensuring security and efficiency. Automating these tasks not only saves time but also reduces the risk of human error.
For more information on the HNG internship program and to learn how to become a world-class developer, visit HNG Internship and HNG Premium.
You can also find the code to the bash script on my GitHub here Linsmed
Top comments (0)