<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Zipporah Kyusya</title>
    <description>The latest articles on Forem by Zipporah Kyusya (@zkyusya).</description>
    <link>https://forem.com/zkyusya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1722072%2Fa4295377-e6ea-40f4-9f41-67f3de84d6db.png</url>
      <title>Forem: Zipporah Kyusya</title>
      <link>https://forem.com/zkyusya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/zkyusya"/>
    <language>en</language>
    <item>
      <title>Automating Linux User Management with a Bash Script</title>
      <dc:creator>Zipporah Kyusya</dc:creator>
      <pubDate>Wed, 03 Jul 2024 08:36:25 +0000</pubDate>
      <link>https://forem.com/zkyusya/automating-linux-user-management-with-a-bash-script-1f07</link>
      <guid>https://forem.com/zkyusya/automating-linux-user-management-with-a-bash-script-1f07</guid>
      <description>&lt;p&gt;Managing user accounts in a Linux environment can be a tedious and error-prone process, especially when dealing with a large number of users. As a SysOps engineer, ensuring that each user is created with the correct permissions, groups, and secure credentials is crucial for maintaining system security and efficiency. &lt;br&gt;
As part of HNG Internship, was assigned a real-world scenario of writing a Bash script designed to automate the process of user and group creation, home directory setup, and password management. This script not only simplifies the user management process but also ensures consistency and security across the system. &lt;/p&gt;

&lt;p&gt;This project is also available on my &lt;a href="https://github.com/Zkyusya/stage1_hnginternship/tree/main" rel="noopener noreferrer"&gt;github repository&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Task&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;Your company has employed many new developers. As a SysOps engineer, write a bash script called &lt;code&gt;create_users.sh&lt;/code&gt;that reads a text file containing the employee’s usernames and group names, where each line is formatted as user;groups.&lt;/p&gt;

&lt;p&gt;The script should create users and groups as specified, set up home directories with appropriate permissions and ownership, generate random passwords for the users, and log all actions to &lt;code&gt;/var/log/user_management.log.&lt;/code&gt; Additionally, store the generated passwords securely in &lt;code&gt;/var/secure/user_passwords.txt.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Ensure error handling for scenarios like existing users and provide clear documentation and comments within the script.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Project Setup&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;To begin with, the script should automate the following;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.Read User and Group Information:&lt;/strong&gt; The script will read from a text file that contains user and group details.&lt;br&gt;
&lt;strong&gt;2. Create User and Group:&lt;/strong&gt; For each user in the file, the script will create a user account and a corresponding personal group.&lt;br&gt;
&lt;strong&gt;3. Assign Additional Groups:&lt;/strong&gt; If additional groups are specified for a user (e.g., hng;hng0,hng1), the script will add the user to those groups.&lt;br&gt;
&lt;strong&gt;4. Create Home Directories:&lt;/strong&gt; A dedicated home directory will be created for each user.&lt;br&gt;
&lt;strong&gt;5. Generate Random Passwords:&lt;/strong&gt; Secure random passwords will be generated for each user and stored in &lt;code&gt;var/secure/user_passwords.csv.&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;6. Log Actions:&lt;/strong&gt; All activities performed by the script will be logged to &lt;code&gt;/var/log/user_management.log.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Creating the User List File&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;The Bash script relies on a text file to define the users and groups it needs to create.&lt;br&gt;
Create a text file named &lt;code&gt;user-list.txt&lt;/code&gt; that contains the usernames and groups.&lt;br&gt;
Example content for &lt;code&gt;user-list.txt&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;light;sudo,dev,www-data
idimma;sudo
mayowa;dev,www-data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can replace the usernames and groups with the names you are working with.&lt;/p&gt;

&lt;p&gt;Next, we create a bash script file that interacts with this text file.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Creating the Bash Script File&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;Now, we create a bash script called &lt;code&gt;create_users.sh&lt;/code&gt; using a text editor (nano).&lt;br&gt;
This script checks for root privileges, reads the user list file, creates users and groups, assigns users to groups, generates random passwords, and logs all actions.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Step by Step Guide on Creating the Bash Script&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Check Root Permissions&lt;/strong&gt;&lt;br&gt;
Ensures the script is run by the root user.&lt;br&gt;
If the script is not run as root user, it exits with an error message.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bash
Copy code
#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
      echo "This script must be run as root"
      exit 1
fi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Validate Input File&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The script checks if a filename was provided as an argument. If not, it exits with a usage message.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
# Check if the input file is provided
if [ -z "$1" ]; then
    echo "Usage: $0 &amp;lt;user_list_file&amp;gt;"
    exit 1
fi

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Create environment variables for the file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create environment variables to hold the paths for the input text file &lt;code&gt;(text_file.txt)&lt;/code&gt;,log file &lt;code&gt;(/var/log/user_management.log)&lt;/code&gt;and the password file &lt;code&gt;(/var/secure/user_passwords.csv)&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Log file and password file paths
INPUT_FILE="$1"
LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Create or clear log and password files with root privileges&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create the log and password files and give them the necessary permissions&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create or clear log and password files with root privileges

mkdir -p /var/log
mkdir -p /var/secure
touch $LOG_FILE
chmod 700 /var/secure  # Set permissions for the log file
: &amp;gt; $LOG_FILE  # Clear the log file
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE  # Set secure permissions for the password file
: &amp;gt; $PASSWORD_FILE  # Clear the password file
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;touch $LOG_FILE&lt;/code&gt;Creates a &lt;code&gt;/var/log/user_management.log&lt;/code&gt;file if they don't exist.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;mkdir -p /var/secure&lt;/code&gt; Creates a &lt;code&gt;/var/secure&lt;/code&gt; directory that will hold the password file.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;chmod 700 /var/secure&lt;/code&gt;Sets the permissions so that only the user has read, write, and execute permissions for the &lt;code&gt;/var/secure&lt;/code&gt; directory&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;touch $PASSWORD_FILE&lt;/code&gt;Creates a &lt;code&gt;/var/secure/user_passwords.csv&lt;/code&gt;file if they don't exist.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;chmod 600 $PASSWORD_FILE&lt;/code&gt;Sets the permissions so that only the user has read and write permissions for the &lt;code&gt;/var/secure/user_passwords.csv&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;: &amp;gt;&lt;/code&gt;command clears the contents of the log and password files.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;5. Generate Random Passwords&lt;/strong&gt;&lt;br&gt;
create the &lt;code&gt;log_message()&lt;/code&gt; and &lt;code&gt;generate_password()&lt;/code&gt; functions. These functions will handle creating log messages for each action and generating user passwords.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Function to generate logs and random passwords
    log_message() {
        echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" &amp;gt;&amp;gt; $LOG_FILE
    }

    generate_password() {
        openssl rand -base64 12
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Process User List&lt;/strong&gt;&lt;br&gt;
Reads the input file line by line, processes each username and associated groups&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Read the user list file and process each line
while IFS=';' read -r username groups || [ -n "$username" ]; do
    username=$(echo "$username" | xargs) # Trim whitespace
    groups=$(echo "$groups" | xargs)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. Create Users and Groups&lt;/strong&gt;&lt;br&gt;
Creates users, personal groups, and additional groups if they do not exist and adds user to each group.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Check if the personal group exists, create one if it doesn't
        if ! getent group "$username" &amp;amp;&amp;gt;/dev/null; then
            echo "Group $username does not exist, adding it now"
            groupadd "$username"
            log_message "Created personal group $username"
        fi


 # Check if the user exists
        if id -u "$username" &amp;amp;&amp;gt;/dev/null; then
            echo "User $username exists"
            log_message "User $username already exists"
        else

            # Create a new user with the created group if the user does not exist
            useradd -m -g $username -s /bin/bash "$username"
            log_message "Created a new user $username"
        fi

# Check if the groups were specified
        if [ -n "$groups" ]; then
            # Read through the groups saved in the groups variable created earlier and split each group by ','
            IFS=',' read -r -a group_array &amp;lt;&amp;lt;&amp;lt; "$groups"
            # Loop through the groups 
            for group in "${group_array[@]}"; do
     # Check if the group already exists
                if ! getent group "$group" &amp;amp;&amp;gt;/dev/null; then
                    # If the group does not exist, create a new group
                    groupadd "$group"
                    log_message "Created group $group."
                fi

                # Add the user to each group
                usermod -aG "$group" "$username"
                log_message "Added user $username to group $group."
            done
        fi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;8. Trimming Whitespace&lt;/strong&gt;&lt;br&gt;
Remove any leading or trailing spaces from the username and groups variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Remove the trailing and leading whitespaces and save each group to the group variable
                group=$(echo "$group" | xargs) # Remove leading/trailing whitespace
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;xargs&lt;/code&gt; command removes any whitespace at the beginning or end of the variable values.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;9. Generating and Setting a User Password&lt;/strong&gt;&lt;br&gt;
Generates a random password for the user, logs it in the password file, and logs the action in the log file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   # Create and set a user password
        password=$(generate_password)
        echo "$username:$password" | chpasswd
        # Save user and password to a file
        echo "$username,$password" &amp;gt;&amp;gt; $PASSWORD_FILE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;10. Feeding the Input File into the Loop&lt;/strong&gt;&lt;br&gt;
The operator, &lt;code&gt;&amp;lt;&lt;/code&gt; tells the while loop to read its input from the file specified by &lt;code&gt;$INPUT_FILE&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  done &amp;lt; "$INPUT_FILE"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;11. Final Log Message&lt;/strong&gt;&lt;br&gt;
Logs the completion of the user creation process.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;log_message "User created successfully"

    echo "Users have been created and added to their groups successfully"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final script file should &lt;a href="https://github.com/Zkyusya/stage1_hnginternship/edit/main/create_users.sh" rel="noopener noreferrer"&gt;look like this &lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Running the Script&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;To execute this script, you need to be logged as a root user and run script using the bash command; &lt;code&gt;create_users.sh user-list.txt&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Ensure the script is executable&lt;/strong&gt; using the following command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chmod +x create_users.sh
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Run the script&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; ./create_user.sh ./user-list.txt
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The use of &lt;code&gt;./&lt;/code&gt;before the script name ensures that the script is executed from the current directory. If the script is located in a different directory, navigate to that directory first using the &lt;code&gt;cd&lt;/code&gt; command.&lt;/p&gt;

&lt;p&gt;Also, check your &lt;code&gt;/var/log/user_management.log&lt;/code&gt; file to see your logs by running this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cat /var/log/user_management.log
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Check your &lt;code&gt;/var/secure/user_passwords.csv&lt;/code&gt; file to see the users and their passwords using the command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cat /var/secure/user_passwords.csv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the script is running successfully, you should see the following in the terminal&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foybmz3ffq70d1pv6af0i.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foybmz3ffq70d1pv6af0i.PNG" alt="Image description" width="781" height="482"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To ensure that the script performs its functions well, I edited the &lt;code&gt;user-list.txt&lt;/code&gt; file for different users and groups. The script successfully created the non-existent users, groups, and added the users to the new groups.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frui5irffzgv07pcf7z2c.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frui5irffzgv07pcf7z2c.PNG" alt="Image description" width="800" height="560"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;Key Points&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;•User and Group Creation:&lt;/strong&gt; The script ensures each user has a personal group with the same name. It handles the creation of multiple groups and adds users to these groups.&lt;br&gt;
&lt;strong&gt;•Home Directory Setup:&lt;/strong&gt; Home directories are created with appropriate permissions and ownership.&lt;br&gt;
&lt;strong&gt;•Password Generation and Security:&lt;/strong&gt; Random passwords are generated and stored securely. Only the file owner can read the password file.&lt;br&gt;
&lt;strong&gt;•Logging:&lt;/strong&gt; All actions are logged for auditing purposes.&lt;br&gt;
This script simplifies the task of user management in a Linux environment, ensuring consistency and security.&lt;/p&gt;

&lt;p&gt;I hope you enjoyed reading this article and can now manage users, groups, and their passwords using bash script.&lt;/p&gt;

&lt;p&gt;Learn more about the HNG Internship and opportunities to grow as a developer:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://hng.tech/internship" rel="noopener noreferrer"&gt;HNGInternship Cohort 11&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://hng.tech/hire" rel="noopener noreferrer"&gt;HNGInternship2024&lt;/a&gt;&lt;/p&gt;

</description>
      <category>devops</category>
      <category>linux</category>
      <category>bash</category>
    </item>
  </channel>
</rss>
