Day 4 | Part 2: Advanced Shell Scripting Projects

Dhruv RajvanshiDhruv Rajvanshi
6 min read

Hello, tech enthusiasts! ๐ŸŒŸ

As part of my DevOps learning journey, I delved into two practical and essential shell scripting projects. These projects not only strengthened my scripting skills but also showcased the power of automation in system administration. Let's dive into the details!

Project 1: User Management Script

Managing users and groups efficiently is crucial in system administration. This project involves creating a comprehensive script that automates various user management tasks, including adding and deleting users, managing groups, changing passwords, and handling errors gracefully.

Key Features:

  1. Adding a User:

    • The script prompts for a username and uses the useradd command to create a new user.

    • It checks if the user was successfully added using $? for error handling.

  2. Adding a Group:

    • Prompts for a group name and creates a new group using groupadd.

    • Includes error checking to ensure the group creation was successful.

  3. Deleting a User:

    • Asks for the username and deletes the user with userdel.

    • It includes error handling to check if the deletion was successful.

  4. Deleting a Group:

    • Prompts for a group name and deletes it using groupdel.

    • Uses error handling to ensure the group was deleted.

  5. Adding a User to a Group:

    • The script allows adding a user to a specific group using usermod -aG.

    • Checks for errors to confirm the addition was successful.

  6. Deleting a User from a Group:

    • Removes a user from a group using gpasswd -d.
  7. Changing the Group of a File:

    • Uses chgrp to change the group ownership of a specified file.
  8. Setting or Changing a User Password:

    • The script prompts for a username and sets or changes the user's password using passwd.

    • This allows administrators or users to easily manage password security.

  9. Error Handling:

    • Utilizes $? to check the exit status of each command and provides appropriate feedback.

This script is a robust solution for managing user accounts and groups, providing a streamlined way to handle common administrative tasks.

#!/bin/bash

# Function to create a user
function create_user {
    read -p "Enter Username: " uname
    read -p "Enter Password: " password

    # Add user with home directory and password
    sudo useradd -m $uname -p $password
    echo "User $uname created successfully"
}

# Function to delete a user
function del_user {
    read -p "Enter username to be deleted: " uname
    sudo deluser $uname
    echo "User $uname deleted successfully"
}

# Function to create a group
function create_group {
    read -p "Enter group name: " groupname
    sudo groupadd $groupname
    echo "Group $groupname created successfully"
}

# Function to delete a group
function del_group {
    read -p "Enter group name to be deleted: " groupname
    sudo delgroup $groupname
    echo "Group $groupname deleted successfully"
}

# Function to add a user to a group
function add_user_to_group {
    read -p "Enter Username: " uname
    read -p "Enter Group name: " groupname
    sudo usermod -aG $groupname $uname
    echo "User $uname added to group $groupname successfully"
}

# Function to remove a user from a group
function remove_user_from_group {
    read -p "Enter Username: " uname
    read -p "Enter Group name: " groupname
    sudo gpasswd -d $uname $groupname
    echo "User $uname removed from group $groupname successfully"
}

# Function to change group ownership of a file
function change_file_group {
    read -p "Enter Filename: " filename
    read -p "Enter Group name: " groupname
    sudo chgrp $groupname $filename
    echo "Group ownership of $filename changed to $groupname"
}

# Function to set or change user password
function change_user_password {
    read -p "Enter Username: " uname
    sudo passwd $uname
    echo "Password for user $uname changed successfully"
}

# Function to handle errors
function handle_error {
    if [ $? -ne 0 ]; then
        echo "An error occurred. Please check your input and try again."
        exit 1
    fi
}

# Main script to call functions based on user input
case $1 in
    1)
    echo "Create User in progress"
    create_user
    handle_error
    ;;
    2)
    echo "Delete User in progress"
    del_user
    handle_error
    ;;
    3)
    echo "Create Group in progress"
    create_group
    handle_error
    ;;
    4)
    echo "Delete Group in progress"
    del_group
    handle_error
    ;;
    5)
    echo "Add User to Group in progress"
    add_user_to_group
    handle_error
    ;;
    6)
    echo "Remove User from Group in progress"
    remove_user_from_group
    handle_error
    ;;
    7)
    echo "Change File Group in progress"
    change_file_group
    handle_error
    ;;
    8)
    echo "Change User Password in progress"
    change_user_password
    handle_error
    ;;
    *)
    echo "Invalid option. Please use: 1 (create user), 2 (delete user), 3 (create group), 4 (delete group), 5 (add user to group), 6 (remove user from group), 7 (change file group), 8 (change user password)"
    ;;
esac

Project 2: Backup and Backup Rotation Script

Data backup is a critical aspect of system management. This project involves creating a script to automate the backup process, ensuring data integrity and availability. The script also includes backup rotation to manage storage efficiently and uses cron for scheduling.

Key Features:

  1. Source and Destination:

    • The script defines source and destination directories for the backup.
  2. Backup Process:

    • Copies files from the source to the destination directory.

    • Uses rsync for efficient file transfer, minimizing data transfer by only copying changed files.

  3. Backup Rotation:

    • Implements a rotation system to manage backups, keeping the latest versions and deleting older ones.

    • For example, it retains the last 7 daily backups and removes backups older than a week.

  4. Automating with Cron:

    • Sets up a cron job to run the backup script at a specified interval, such as daily at midnight.

    • Ensures regular backups without manual intervention.

#!/bin/bash

# Prompt for source and destination paths
read -p "Enter the source path: " source
read -p "Enter the destination path: " destination

# Generate a timestamp for the backup
timestamp=$(date '+%Y-%m-%d-%H-%M-%S')

# Function to create a backup
function create_backup {
    # Define the backup directory
    backup_dir="$destination/backup_$timestamp"

    # Create a zip file of the source directory
    zip -r "$backup_dir.zip" "$source" > /dev/null

    # Check if the backup was successful
    if [ $? -eq 0 ]; then
        echo "Backup created successfully at $backup_dir.zip"
    else
        echo "Backup failed for $timestamp. Please check your source and destination paths."
    fi
}

# Function to handle backup rotation
function backup_rotation {
    # List all backup files sorted by modification time, with the most recent first
    backups=($(ls -t "$destination/backup_"*.zip))

    # Check if the number of backups exceeds the limit (e.g., 3)
    if [ "${#backups[@]}" -gt 3 ]; then
        # Select backups to remove (older ones)
        remove_backups=("${backups[@]:3}")
        for backup in "${remove_backups[@]}"; do
            rm "$backup"
            echo "Removed old backup: $backup"
        done
    fi
}

# Create a backup
create_backup

# Perform backup rotation
backup_rotation

Conclusion

These projects showcase the power and flexibility of shell scripting in system administration. From managing users and groups to automating backups and ensuring data integrity, shell scripts can significantly simplify complex tasks and improve efficiency. Completing these projects has been an invaluable experience, deepening my understanding of shell scripting and automation.

Stay tuned for more updates as I continue exploring the world of DevOps and system administration!

0
Subscribe to my newsletter

Read articles from Dhruv Rajvanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dhruv Rajvanshi
Dhruv Rajvanshi