๐Ÿš€ Advanced Linux Shell Scripting and User Management!

๐Ÿš€ Advanced Linux Shell Scripting and User Management!

ยท

8 min read

Hello, DevOps enthusiasts! Today, we're diving into the advanced realms of Linux Shell Scripting and exploring the crucial aspects of User Management. Let's unleash the power of scripting for efficient directory creation and safeguarding our work.

So, let's begin!!!

Task 1: Dynamic Directory Creation with Shell Scripting:

Ever wondered how to create 90 directories in seconds? Discover the magic of Shell Scripting with the task of creating directories dynamically. Use loops and command-line arguments to generate directories with a dynamic name.

Well then, let's have a look at its script, and I'll try to make it understandable for you.

#!/bin/bash

# Check if the correct number of arguments are provided
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <directory_name> <start_number> <end_number>"
    exit 1
fi

# Assign arguments to variables
directory_name="$1"
start_number="$2"
end_number="$3"

# Loop to create directories
for ((i = start_number; i <= end_number; i++)); do
    dir_name="${directory_name}${i}"
    mkdir "$dir_name"
    echo "Created directory: $dir_name"
done

echo "Directories created successfully!"

Save this script in a file named createDirectories.sh. Make it executable using:

chmod +x createDirectories.sh

Example 1:

./createDirectories.sh day 1 90

Example 2:

./createDirectories.sh Movie 20 50

This script will create the specified number of directories with dynamic names as per your requirements.

Let's Breakdown this script:

  1. Shebang (#!/bin/bash):

    • This line indicates that the script should be interpreted and executed by the Bash shell.
  2. Check for Correct Number of Arguments:

     if [ "$#" -ne 3 ]; then
         echo "Usage: $0 <directory_name> <start_number> <end_number>"
         exit 1
     fi
    
    • $# represents the number of arguments passed to the script.

    • If the number of arguments is not equal to 3, it prints a usage message and exits with a non-zero status.

  3. Assign Arguments to Variables:

     directory_name="$1"
     start_number="$2"
     end_number="$3"
    
    • These lines assign the first, second, and third command-line arguments to variables for easier reference.
  4. Loop to Create Directories:

     for ((i = start_number; i <= end_number; i++)); do
         dir_name="${directory_name}${i}"
         mkdir "$dir_name"
         echo "Created directory: $dir_name"
     done
    
    • A for loop is used to iterate from the start_number to the end_number.

    • Inside the loop, a dynamic directory name is formed by concatenating the directory_name and the loop variable i.

    • mkdir is used to create the directory, and an echo statement prints a message indicating the creation.

  5. End of Script:

     echo "Directories created successfully!"
    
    • Prints a message indicating that the directories have been created successfully.

How to Use:

  • Save the script in a file named createDirectories.sh.

  • Make it executable using chmod +x createDirectories.sh.

  • Run the script with the desired arguments, for example:

      ./createDirectories.sh day 1 5
    

    This will create directories named day1, day2, day3, day4, and day5 in the current working directory.

Task 2: Create a Script to backup all your work done till now:

Here is a simple script for creating backups:

#!/bin/bash

# Specify the directory to backup
source_directory="/path/to/your/source/directory"

# Specify the backup folder
backup_folder="/path/to/your/backup/folder"

# Create a timestamp for the backup file
timestamp=$(date "+%Y%m%d%H%M%S")

# Specify the backup file name with timestamp
backup_file="backup_$timestamp.tar.gz"

# Create the backup
tar -czvf "$backup_folder/$backup_file" "$source_directory"

# Check if the backup was successful
if [ $? -eq 0 ]; then
    echo "Backup completed successfully. Backup file: $backup_folder/$backup_file"
else
    echo "Backup failed."
fi

Explanation:

  1. Specify Source Directory and Backup Folder:

    • Set the source_directory variable to the path of the directory you want to back up.

    • Set the backup_folder variable to the path where you want to store the backup.

  2. Create Timestamp:

     timestamp=$(date "+%Y%m%d%H%M%S")
    
    • Generate a timestamp using the date command in the format YYYYMMDDHHMMSS.
  3. Specify Backup File Name:

     backup_file="backup_$timestamp.tar.gz"
    
    • Create the backup file name by combining a prefix ("backup_"), the timestamp, and the file extension (".tar.gz").
  4. Create Backup Using tar Command:

     tar -czvf "$backup_folder/$backup_file" "$source_directory"
    
    • Create a compressed archive (tar.gz) of the source directory and save it with the specified file name in the backup folder.
  5. Check Backup Status:

     if [ $? -eq 0 ]; then
         echo "Backup completed successfully. Backup file: $backup_folder/$backup_file"
     else
         echo "Backup failed."
     fi
    
    • Check the exit status of the tar command. If it's 0, the backup was successful; otherwise, it failed.

Note:

  • Make sure to replace /path/to/your/source/directory and /path/to/your/backup/folder with the actual paths.

  • Adjust the script as needed for your specific setup.

Task 3: Basics cron and crontab:

Cron:

Cron is a time-based job scheduler in Linux operating systems. It allows users to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. These scheduled jobs are referred to as "Cron Jobs."

Crontab:

Crontab is the command used to interact with the cron daemon. It allows users to create, edit, list, and remove cron jobs. Each user on a Linux system can have their own crontab file that contains their scheduled tasks.

Basic Syntax:

The basic syntax of a cron job entry in the crontab file is as follows:

* * * * * command_to_be_executed
  • The five asterisks represent the time and date fields, indicating when the command should be executed.

  • The command_to_be_executed is the actual command or script to run.

Time and Date Fields:

The five fields in a cron job entry represent the following:

  1. Minute (0 - 59)

  2. Hour (0 - 23)

  3. Day of month (1 - 31)

  4. Month (1 - 12)

  5. Day of week (0 - 6) (Sunday is both 0 and 7)

Examples:

  • Run a script every day at 2:30 PM:

      30 14 * * * /path/to/your/script.sh
    
  • Run a command every Monday at 3:45 AM:

      45 3 * * 1 /path/to/your/command
    

Commands:

  • To edit the crontab for the current user:

      crontab -e
    
  • To list the current user's crontab entries:

      crontab -l
    
  • To remove the current user's crontab:

      crontab -r
    

By using Cron and Crontab, you can automate the execution of your backup script at specified intervals. For example, you can schedule the backup script to run every day at midnight to ensure regular backups of your work.

Task 4: User Management in Linux:

Why User Management?

1. Security:

  • Access Control: Assigns specific privileges to users, limiting unauthorized access to sensitive data and system settings.

  • Isolation: Ensures users operate within their designated areas, preventing accidental or intentional interference with others' work.

2. Accountability:

  • Audit Trail: Enables tracking of user activities for auditing purposes. This accountability is crucial for maintaining system integrity.

3. Resource Management:

  • Resource Allocation: Manages the distribution of resources, ensuring fair and optimal usage among different users.

  • Quotas: Controls storage and other resource usage to prevent one user from monopolizing resources.

4. Collaboration:

  • Group Management: Facilitates collaboration by grouping users with common tasks or projects, simplifying permission and access assignments.

5. Administrative Efficiency:

  • User Control: Simplifies the administration of individual users and their associated settings.

  • Password Policies: Allows enforcement of password policies to enhance system security.

Now, What is user management?

User management in Linux involves overseeing and controlling the activities of users on a system. It encompasses a range of tasks related to creating, modifying, and removing user accounts, as well as establishing and managing user groups. This management is crucial for maintaining security, controlling access to resources, and fostering collaboration. Let's break down its key aspects:

1. User Accounts:

  • Creation: Adding new users to the system with unique identifiers (User IDs or UIDs) and other relevant information.

  • Modification: Adjusting user attributes such as password, home directory, and default shell.

  • Deletion: Removing user accounts that are no longer necessary.

2. Group Management:

  • Creation: Establishing groups to organize and manage users based on shared responsibilities or projects.

  • Modification: Adjusting group properties, such as group name or members.

  • Deletion: Removing groups that are no longer required.

3. Password Policies:

  • Password Assignment: Setting or updating user passwords for authentication.

  • Password Expiry: Implementing policies to ensure periodic password changes for enhanced security.

  • Password Recovery: Assisting users in regaining access to their accounts.

4. Access Control:

  • Permissions: Granting or restricting access to files, directories, and system resources based on user roles.

  • Privileges: Assigning specific rights to users, such as the ability to execute administrative commands.

5. User Information:

  • User ID (UID) and Group ID (GID): Assigning unique identifiers to users and groups for system recognition.

  • User Information Files: Storing details like usernames, home directories, and shell preferences in /etc/passwd and /etc/shadow.

User Types:

  • Root User (Superuser): The superuser has ultimate control, performing critical tasks. Identified by UID 0.

  • System Users: Used for system processes, with UIDs from 1 to 999.

  • Local Users: Regular users who interact with the system, starting from UID 1000.

User Commands:

  • useradd: Adds a new user to the system.

  • passwd: Sets or changes a user's password.

  • userdel: Deletes a user account.

  • usermod: Modifies a user account.

  • id: Displays user and group information.

File Locations:

  • /etc/passwd: Stores user account information.

  • /etc/shadow: Holds encrypted passwords.

  • /etc/group: Contains group information.

  • /etc/sudoers: Configures sudo permissions.

Task 5: Create 2 users and just display their Usernames:

There are many ways to complete this task. i'll show you a script that does the same task:

# Create User1
sudo useradd User1

# Set password for User1
sudo passwd User1

# Create User2
sudo useradd User2

# Set password for User2
sudo passwd User2

# Display Usernames
echo "User1's Username: $(id -un User1)"
echo "User2's Username: $(id -un User2)"

These commands perform the following actions:

  1. Create Users: useradd is used to add users (User1 and User2) to the system.

  2. Set Passwords: passwd is used to set passwords for the newly created users.

  3. Display Usernames: id -un is used to display the usernames of the created users.

Well, That's All for today. Stay cool, stay humble. Happy coding!

ย