Automation with Bash

Enhancing Efficiency with Automation and Bash Scripting: A Practical Guide

In today’s fast-paced IT environments, automation is a game-changer. It saves time, reduces human error, and ensures consistency across systems. One of the most powerful tools for automation is Bash scripting, which allows administrators to automate routine tasks in Unix-based systems. In this article, we’ll explore the power of Bash scripting through a practical example: automating user and group management.

What is Bash Scripting?

Bash (Bourne Again SHell) is a command processor that runs in a text window where users can type commands. Bash scripting involves writing a series of commands in a file, allowing them to be executed sequentially. This is incredibly useful for automating repetitive tasks, such as managing users, performing system maintenance, or deploying software.

Why Automate User and Group Management?

Managing users and groups is a common task for system administrators, especially in large organizations where new employees join frequently. Automating this process ensures that all users are created with the correct permissions and groups, home directories are set up properly, and passwords are securely generated and stored.

Example Project: Automating User Creation with Bash

Let’s dive into a practical example where we automate the process of user and group creation using a Bash script.

Project Requirements
  • Create a script named create_users.sh.
  • Read usernames and groups from a text file where each line is formatted as user;groups.
  • Create users and assign them to their respective groups.
  • Set up home directories with appropriate permissions.
  • Generate random passwords for users and store them securely.
  • Log all actions to /var/log/user_management.log.
Script Breakdown

Here’s a detailed look at the script:

  1. Ensure the Script is Run as Root:

The script checks if it is being run as root, as creating users and modifying system files requires root privileges.

```
if [ "$(id -u)" -ne 0 ]; then echo "This script must be run as root" 1>&2 exit 1
fi
```
Enter fullscreen mode
Exit fullscreen mode
  1. Check for Input File:

Validates that an input file is provided as an argument to the script.

```
if [ -z "$1" ]; then echo "Usage: $0 <name-of-text-file>" exit 1
fi INPUT_FILE=$1
```
Enter fullscreen mode
Exit fullscreen mode
  1. Initialize Log and Password Files:

Defines log and password files, creates the /var/secure directory if it doesn’t exist, and sets appropriate permissions.

```
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv" mkdir -p /var/secure
chmod 700 /var/secure
```
Enter fullscreen mode
Exit fullscreen mode
  1. Password Generation Function:

Defines a function to generate a random 12-character password.

```
generate_password() { tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
```
Enter fullscreen mode
Exit fullscreen mode
  1. Process the Input File:

Reads each line from the input file, extracts the username and groups, and processes them.

```
while IFS=';' read -r username groups; do username=$(echo "$username" | xargs) groups=$(echo "$groups" | xargs) if [ -z "$username" ]; then continue fi if id "$username" &>/dev/null; then echo "User $username already exists. Skipping..." | tee -a "$LOG_FILE" continue fi useradd -m "$username" | tee -a "$LOG_FILE" usermod -g "$username" "$username" | tee -a "$LOG_FILE" if [ -n "$groups" ]; then IFS=',' read -ra ADDR <<< "$groups" for group in "${ADDR[@]}"; do group=$(echo "$group" | xargs) if ! getent group "$group" >/dev/null; then groupadd "$group" | tee -a "$LOG_FILE" fi usermod -aG "$group" "$username" | tee -a "$LOG_FILE" done fi password=$(generate_password) echo "$username:$password" | chpasswd | tee -a "$LOG_FILE" echo "$username,$password" >> "$PASSWORD_FILE" chown -R "$username:$username" "/home/$username" | tee -a "$LOG_FILE" chmod 700 "/home/$username" | tee -a "$LOG_FILE" echo "Created user $username with groups $groups" | tee -a "$LOG_FILE" done < "$INPUT_FILE"
```
Enter fullscreen mode
Exit fullscreen mode
  1. Secure the Password File:

Ensures that the password file has restricted permissions so only the file owner can read it.

```
chmod 600 "$PASSWORD_FILE"
echo "User creation process completed." | tee -a "$LOG_FILE"
```
Enter fullscreen mode
Exit fullscreen mode
Running the Script
  1. Create the Script File:
    Create the script file using a text editor.

    sudo nano create_users.sh
    
  2. Make the Script Executable:
    Change the script’s permissions to make it executable.

    sudo chmod +x create_users.sh
    
  3. Create the Input File:
    Create the input file with usernames and groups using a text editor.

    sudo nano users.txt
    
  4. Run the Script:
    Execute the script with the input file as an argument.

    sudo ./create_users.sh users.txt
    
  5. Verify the Output:
    Check the log and password files to verify the actions performed by the script.

    sudo cat /var/log/user_management.log
    sudo cat /var/secure/user_passwords.csv
    

Benefits of Automation

  1. Efficiency: Automating repetitive tasks saves time, allowing administrators to focus on more critical issues.
  2. Consistency: Automated scripts ensure that tasks are performed the same way every time, reducing the risk of errors.
  3. Security: Automating password generation and secure storage minimizes the risk of weak or exposed passwords.

Image description

Conclusion

Bash scripting is a powerful tool for automating system administration tasks. By automating user and group management, administrators can ensure that new employees are onboarded quickly and securely. This example demonstrates how a simple script can significantly enhance operational efficiency and security.

For more information about automation and learning opportunities, check out the HNG Internship and HNG Hire programs.
Also checkout my github page for more projects
https://github.com/OlavicDev/User-and-Group-Management-with-Bash.git


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top