<?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>DEV Community: Praise Nwanguma</title>
    <description>The latest articles on DEV Community by Praise Nwanguma (@bezaleelstone).</description>
    <link>https://dev.to/bezaleelstone</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%2F1729847%2F8e08bd33-c633-484b-bbe6-946d286cf9d8.jpg</url>
      <title>DEV Community: Praise Nwanguma</title>
      <link>https://dev.to/bezaleelstone</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/bezaleelstone"/>
    <language>en</language>
    <item>
      <title>Automating User and Group Management in Linux using Bash scripting: A Comprehensive Guide</title>
      <dc:creator>Praise Nwanguma</dc:creator>
      <pubDate>Thu, 04 Jul 2024 13:16:24 +0000</pubDate>
      <link>https://dev.to/bezaleelstone/automating-user-and-group-management-in-linux-using-bash-scripting-a-comprehensive-guide-37d1</link>
      <guid>https://dev.to/bezaleelstone/automating-user-and-group-management-in-linux-using-bash-scripting-a-comprehensive-guide-37d1</guid>
      <description>&lt;h2&gt;
  
  
  INTRODUCTION
&lt;/h2&gt;

&lt;p&gt;Automation is an important aspect of DevOps enginneering. It reduces friction, saves time, and boosts efficiency and productivity.&lt;br&gt;
In this article, we will explore a Bash script designed to automate the creation of users and groups based on input from a text file. Each user will have a personal group with the same name, and additional groups can be specified in the input file. The script also logs out the actions and securely stores generated passwords.&lt;/p&gt;

&lt;h2&gt;
  
  
  TASK:
&lt;/h2&gt;

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

&lt;ul&gt;
&lt;li&gt;Create users and groups as specified,&lt;/li&gt;
&lt;li&gt;Set up home directories with appropriate permissions and ownership,&lt;/li&gt;
&lt;li&gt;Generate random passwords for the users,&lt;/li&gt;
&lt;li&gt;Log all actions to &lt;code&gt;/var/log/user_management.log&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;Store the generated passwords securely in &lt;code&gt;/var/secure/user_passwords.txt&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Ensure error handling for scenarios like existing users.&lt;/li&gt;
&lt;li&gt;Each User must have a personal group with the same group name as the username, this group name will not be written in the text file.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  SCRIPT BREAKDOWN
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Check for Input File and Define Variables:&lt;/strong&gt; The script starts off by declaring the shebang  ('#!/bin/bash') to specify the interpreter. If statement is use to check if a valid input file was provided in the command line, then initialises a variable to store the input file, logs and password.
&lt;/li&gt;
&lt;/ol&gt;

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

# Check if the input file is provided
if [ $# -eq 0 ]; then
  echo "Usage: $0 &amp;lt;input_file&amp;gt;"
  exit 1
fi

#Initialize variables for input file from the command line
input_file=$1

#Initialize variables for log files and password files
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create the Neccesary Directories:&lt;/strong&gt; This block ensures that the neccesary directories are created and it sets the appropriate permissions to secure the password file.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create log and password directories if they don't exist
sudo mkdir -p /var/log /var/secure
sudo touch "$log_file" "$password_file"
sudo chmod 600 "$password_file"

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

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The Log Function:&lt;/strong&gt; This function in the script appends messages with timestamps to the log file. This helps in tracking the actions performed by the script.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Function to log messages
log() {
  local message="$1"
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | sudo tee -a "$log_file"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Function to Generate random Passwords:&lt;/strong&gt; This function uses &lt;code&gt;/dev/urandom&lt;/code&gt;, a secure random number generator, to generate a random 12-character password for the users once they are created.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;generate_password() {
  tr -dc A-Za-z0-9 &amp;lt;/dev/urandom | head -c 12
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Main Script:&lt;/strong&gt; The main script is a while loop that is made of of two main blocks- The user processing and the group processing. I explain better below.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;i. &lt;strong&gt;User Processing:&lt;/strong&gt; This block carries out a number of actions as follows-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Read Input File:&lt;/strong&gt; The script uses IFS=';' to read each line from the input file, splitting it into username and groups using the  read -r command.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Create Personal group for users:&lt;/strong&gt; Here a personal group for users is being created. This group wasn't included in the txt file.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Create Users:&lt;/strong&gt; If the user does not already exist (&lt;code&gt;id "$username"&lt;/code&gt;), the script creates the user along with a personal group (&lt;code&gt;-g "$username"&lt;/code&gt;) and sets up the home directory with appropriate permissions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Password Management&lt;/strong&gt;: The script calls the &lt;code&gt;generate_password()&lt;/code&gt; function which generates a random password, assigns it to the user, and stores it securely.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Process each line in the input file
while IFS=';' read -r username groups; do
  if id "$username" &amp;amp;&amp;gt;/dev/null; then
    log "User $username already exists."
  else

    # Create a personal group for the user
    if getent group "$username" &amp;amp;&amp;gt;/dev/null; then
      log "Group $username already exists."
    else
      sudo groupadd "$username"
      log "Personal group $username created."
    fi

    # Create the user with a home directory
    sudo useradd -m -g "$username" "$username"
    if [ $? -eq 0 ]; then
      log "User $username created."
    else
      log "Failed to create user $username."
      continue
    fi

    # Set up home directory with appropriate permissions
    sudo chmod 700 "/home/$username"
    sudo chown "$username:$username" "/home/$username"
    log "Home directory for $username set up with correct permissions."

    # Generate a random password and set it for the user
    password=$(generate_password)
    echo "$username:$password" | sudo chpasswd
    if [ $? -eq 0 ]; then
      log "Password for $username set."
    else
      log "Failed to set password for $username."
      continue
    fi

    # Store the password securely
    echo "$username:$password" | sudo tee -a "$password_file" &amp;gt; /dev/null
  fi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Group Processing:&lt;/strong&gt; This block processes additional groups from the input file, creating them if necessary, and adds the user to these groups.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Read input file with IFS:&lt;/strong&gt; IFS=',': The IFS is set to a comma, which means the read command will split the input string based on commas and store the groups in an array. This will enable the user to be added to multiple groups according to the input file.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Read Groups in Array:&lt;/strong&gt; After the groups have been stored in an array, a for loop is used to iterate over each group in the array.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Check if groups exist and Creats groups:&lt;/strong&gt; An if statement in the script checks if the group already exists, then creats one. It logs out the output of both cases.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Add User:&lt;/strong&gt; Finally the users are added to their appropriate groups.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Process groups
  IFS=',' read -ra group_array &amp;lt;&amp;lt;&amp;lt; "$groups"
  for group in "${group_array[@]}"; do
    if getent group "$group" &amp;amp;&amp;gt;/dev/null; then
      log "Group $group already exists."
    else
      sudo groupadd "$group"
      log "Group $group created."
    fi

    # Add the user to the group
    sudo usermod -aG "$group" "$username"
    log "User $username added to group $group."
  done
done &amp;lt; "$input_file"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Execute Script
&lt;/h2&gt;

&lt;p&gt;Make the script executable by running &lt;code&gt;chmod +x create_users.sh&lt;/code&gt; in your terminal&lt;br&gt;
Run the script with the input file like this &lt;code&gt;./create_users.sh input.txt&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This was a stage 1 DevOps Task at &lt;a href="https://hng.tech/internship"&gt;HNG Internship&lt;/a&gt;. You can check for available roles at &lt;a href="https://hng.tech/hire"&gt;HNG Hire&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can find entire code here: &lt;a href="https://github.com/Bezaleelstone/User-group-automation-on-linux-with-bashscript.git"&gt;https://github.com/Bezaleelstone/User-group-automation-on-linux-with-bashscript.git&lt;/a&gt;&lt;/p&gt;

</description>
      <category>linux</category>
      <category>bash</category>
      <category>automation</category>
      <category>sysop</category>
    </item>
  </channel>
</rss>
