Automating a Bash Script
Sophie Ejikeme
Posted on July 3, 2024
Ever wondered how you can simplify a monotonous task? Worry no more! But before we delve further, what do we actually mean by a script? And why do we have a script? In the context of Bash, a script is a text file containing a series of Bash commands to be executed sequentially.
So, a Bash script will contain some commands intended to carry out a function or task.
A Realistic Scenario
Imagine you have a repetitive task to carry out. Or imagine that you want to add a good number of employees to a group, a Bash script can automate this for you. Such script should be able to perform the tasks below:
- Create users and groups
- Set up home directories with appropriate permissions and ownership
- Generate random passwords for the users
- Log all actions to /var/log/user_management.log.
- Store the generated passwords securely in /var/secure/user_passwords.txt
Now, how can this be done?
Explanation
Step 1: Check root privileges
Since user and group management commands require administrative access, the script verifies if it’s run as root.
Check if script is run as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
Step 2: Read the user file
The script checks if the user file is provided as an argument and uses it when it is executed
Check if the file with users and their corresponding groups exists
if ["$#" -ne 1]; then
echo "Use: $0 "
exit 1
fi
Step 3: Initialize password and log file
We will initialize the values of the log and password file. If the files do not exist, we need to create them. For the password file, we need to set appropriate permissions where only the user can read and write it.
INPUT_FILE=$1
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
Ensure log file exists and has correct permissions
touch "$LOG_FILE"
chmod 600 "$LOG_FILE"
Ensure password file exists and has correct permissions
touch "$PASSWORD_FILE"
chmod 600 "$PASSWORD_FILE"
Step 4: Create a user function
The purpose of the function is :
Checking if the user already exists.
Creating a personal group for each user.
Creating the user and adding them to specified groups.
Generating a random password.
Setting the user’s password.
Logging the action and storing the password securely.
script to create users and groups from a file
if [ $# -ne 1 ]; then
echo "Usage: $0 "
exit 1
fi
INPUT_FILE=$1
Log and password file paths
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
!/bin/bash
Script: create_users.sh
Description: This script Creates users and groups based on input file, sets up home directories,
generates random passwords, and logs all actions.
Usage: ./create_users.sh
Check if script is run as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
Check if input file is provided
if [[ $# -eq 0 ]]; then
echo "Usage: $0 "
exit 1
fi
INPUT_FILE=$1
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
Ensure log file exists and has correct permissions
touch "$LOG_FILE"
chmod 600 "$LOG_FILE"
Ensure password file exists and has correct permissions
touch "$PASSWORD_FILE"
chmod 600 "$PASSWORD_FILE"
Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}
Function to generate a random password
generate_password() {
openssl rand -base64 12 | tr -d '=+/'
}
Read input file line by line
while IFS=';' read -r username groups; do
# Skip empty lines
[[ -z "$username" ]] && continue
Create user if it doesn't exist
if id "$username" &>/dev/null; then
log_message "User $username already exists. Skipping user creation."
else
useradd -m -s /bin/bash "$username"
if [[ $? -eq 0 ]]; then
log_message "User $username created successfully."
else
log_message "Failed to create user $username."
continue
fi
fi
Set up home directory permissions
chmod 700 "/home/$username"
log_message "Set permissions for /home/$username"
Generate and set random password
password=$(generate_password)
echo "$username:$password" | chpasswd
echo "$username:$password" >> "$PASSWORD_FILE"
log_message "Set password for user $username"
Create and add user to groups
IFS=',' read -ra group_array <<< "$groups"
for group in "${group_array[@]}"; do
if ! getent group "$group" &>/dev/null; then
groupadd "$group"
log_message "Group $group created."
fi
usermod -aG "$group" "$username"
log_message "Added user $username to group $group"
done
done < "$INPUT_FILE"
log_message "User creation process completed."
echo "User creation process completed. Check $LOG_FILE for details."
Running the Script
- Create users file Add your users and their groups in the format user;groups. Save and close the file.
- Make the file and the script executable
chmod +x users.txt
chmod +x create_script.sh
- Run the Script
sudo ./create_script.sh users.txt
Points to Consider
Save this script as create_users.sh. Open your terminal, for example, Ubuntu, type nano create_users.sh
Ensure you save and exit (just type ctrl o, click enter and then ctrl x).Make it executable e.g chmod +x create_users.sh
Create a text file where you'll have the names of the users and their groups e.g nano users.txt
type names of employees using this format - Jones;Dev,Audit
Conclusion
This automation promotes time saving, productivity and efficiency.
About HNG Internship
HNG Internship is a fast-paced bootcamp for learning digital skills. It's focused on advanced learners and those with some pre-knowledge, and it gets people into shape for job offers. In the HNG bootcamp, you work in teams to build apps and solve problems. For more information on what they offer, you can reach them through the link below.
https://hng.tech/internship, https://hng.tech/hire
Posted on July 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.