<?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: Olawale</title>
    <description>The latest articles on Forem by Olawale (@hellowale).</description>
    <link>https://forem.com/hellowale</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%2F1720256%2Fdb41926f-864e-4b95-9514-006afe92105b.jpg</url>
      <title>Forem: Olawale</title>
      <link>https://forem.com/hellowale</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/hellowale"/>
    <language>en</language>
    <item>
      <title>Automating User and Group Management on Linux with a Bash Script</title>
      <dc:creator>Olawale</dc:creator>
      <pubDate>Fri, 05 Jul 2024 09:39:44 +0000</pubDate>
      <link>https://forem.com/hellowale/automating-user-and-group-management-on-linux-with-a-bash-script-46gl</link>
      <guid>https://forem.com/hellowale/automating-user-and-group-management-on-linux-with-a-bash-script-46gl</guid>
      <description>&lt;p&gt;Hey there!&lt;/p&gt;

&lt;p&gt;I’m excited to share the details of my Stage 1 task for the HNG DevOps Internship. This task involved creating a Bash script to automate the process of user and group management on a Linux system&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.&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 /var/log/user_management.log. Additionally, store the generated passwords securely in /var/secure/user_passwords.txt.&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;h2&gt;
  
  
  Sample Input
&lt;/h2&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;h2&gt;
  
  
  Solution
&lt;/h2&gt;

&lt;p&gt;The script solves the problem by following these procedures:&lt;/p&gt;

&lt;p&gt;Step 1: Reading the Input File&lt;br&gt;
First, we read the input file using a function that adds the users to a global variable called users and the groups to another variable called group_list. It does this simultaneously, allowing the index of each user in users to match their corresponding groups in group_list. We also ensure the user has entered a valid input file before running this.&lt;/p&gt;

&lt;p&gt;Here's the code that does all of this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;declare -a users
declare -a group_list

# Function to read and parse the input file
read_input_file() {
  local filename="$1"
  while IFS=';' read -r user groups; do
    users+=("$(echo "$user" | xargs)")
    group_list+=("$(echo "$groups" | tr -d '[:space:]')")
  done &amp;lt; "$filename"
}

# Check for input file argument
if [[ $# -ne 1 ]]; then
  echo "Usage: $0 &amp;lt;input_file&amp;gt;"
  exit 1
fi

input_file="$1"
echo "Reading input file: $input_file"
read_input_file "$input_file"

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

&lt;/div&gt;



&lt;p&gt;Step 2: Creating Required Files and Directories&lt;br&gt;
Next, we create the required files and their directories if they don't already exist using this code:&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="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"

# Create log and password files if they do not exist
mkdir -p /var/log /var/secure
touch "$log_file"
touch "$password_file"
chmod 600 "$password_file"

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

&lt;/div&gt;



&lt;p&gt;Step 3: Creating Users and Groups&lt;br&gt;
At this point, we have a list of the users in users, a list of their corresponding groups in group_list, and all the files we need to store valuable information such as logs and the passwords of the users we created.&lt;/p&gt;

&lt;p&gt;Now, we use a for loop to iterate over each user and their corresponding groups with an index. Since we created the users and group_list arrays simultaneously by looping over each line in the file, the user at index 0 in users needs to be added to the groups at index 0 in group_list. So our for loop will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Process each user
for ((i = 0; i &amp;lt; ${#users[@]}; i++)); do
  username="${users[i]}"
  user_groups="${group_list[i]}"

  if [[ "$username" == "" ]]; then
    continue  # Skip empty usernames
  fi

  create_user_with_group "$username"
  set_user_password "$username"
  add_user_to_groups "$username" "$user_groups"
done

echo "User creation and group assignment completed." | tee -a "$log_file"

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

&lt;/div&gt;



&lt;p&gt;So username is the user we are working on and user_groups are the groups we are adding them to.&lt;/p&gt;

&lt;p&gt;Next, we check if the user exists. If they do, we just continue with the next iteration; else, we create them with this code:&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 create a user with its personal group
create_user_with_group() {
  local username="$1"
  if id "$username" &amp;amp;&amp;gt;/dev/null; then
    echo "User $username already exists." | tee -a "$log_file"
  else
    groupadd "$username"
    useradd -m -g "$username" -s /bin/bash "$username"
    echo "Created user $username with personal group $username." | tee -a "$log_file"
  fi
}

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

&lt;/div&gt;



&lt;p&gt;Step 4: Setting User Password&lt;br&gt;
We set a password for the user by using openssl to generate 12 random base64 characters. We then store the user's password in /var/secure/user_passwords.txt.&lt;/p&gt;

&lt;p&gt;These are done using the code below:&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 set a password for the user
set_user_password() {
  local username="$1"
  local password=$(openssl rand -base64 12)
  echo "$username:$password" | chpasswd
  echo "$username,$password" &amp;gt;&amp;gt; "$password_file"
  echo "Password for $username set and stored." | tee -a "$log_file"
}

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

&lt;/div&gt;



&lt;p&gt;Step 5: Adding Users to Groups&lt;br&gt;
Next, we add the user to their groups. We do this by first checking if the group exists. If it doesn't, we create the group and then add the user to the group.&lt;/p&gt;

&lt;p&gt;See the code below:&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 add user to additional groups
add_user_to_groups() {
  local username="$1"
  IFS=',' read -r -a groups &amp;lt;&amp;lt;&amp;lt; "$2"
  for group in "${groups[@]}"; do
    if ! getent group "$group" &amp;amp;&amp;gt;/dev/null; then
      groupadd "$group"
      echo "Group $group created." | tee -a "$log_file"
    fi
    usermod -aG "$group" "$username"
    echo "Added $username to group $group." | tee -a "$log_file"
  done
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;And just like that, all new employees now have user profiles! You can also reuse this script for new employees. Exciting, right?&lt;/p&gt;

&lt;p&gt;You will also notice how I appropriately log each event in the log file and gracefully handle failures in each command. So even if we run into unexpected problems in our execution, we not only end the program gracefully, but we also have a log for further investigation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Automation
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Efficiency: Automates repetitive tasks, freeing up time for more critical activities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Consistency: Ensures that user and group configurations are applied uniformly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Security: Randomly generated passwords enhance security, and storing them securely minimizes risks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Auditing: Detailed logging helps in tracking changes and troubleshooting.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Learn More
&lt;/h2&gt;

&lt;p&gt;If you're interested in advancing your career in tech, consider joining the HNG Internship program, visit &lt;a href="https://hng.tech/internship"&gt;HNG Internsip&lt;/a&gt; or &lt;a href="https://hng.tech/premium"&gt;HNG Premium&lt;/a&gt;. It's an excellent opportunity to gain hands-on experience and learn from industry professionals.&lt;/p&gt;

&lt;p&gt;For those looking to hire top tech talent, HNG Hire connects you with skilled developers who have undergone rigorous training.&lt;/p&gt;

&lt;p&gt;That's it for now, but stay tuned for the exciting tasks in Stage 2! &lt;/p&gt;

</description>
      <category>bash</category>
      <category>devops</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Automating User and Group Management on Linux with a Bash Script</title>
      <dc:creator>Olawale</dc:creator>
      <pubDate>Fri, 05 Jul 2024 08:42:13 +0000</pubDate>
      <link>https://forem.com/hellowale/automating-user-and-group-management-on-linux-with-a-bash-script-2o7j</link>
      <guid>https://forem.com/hellowale/automating-user-and-group-management-on-linux-with-a-bash-script-2o7j</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Managing users and groups on a Linux system can be a daunting task, especially when onboarding new employees. As a SysOps engineer, automating these tasks can save time and reduce errors. In this article, we'll explore a bash script called create_users.sh that automates user creation, password management, and group assignments. This script reads from an input file and logs all actions, ensuring a smooth and auditable process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Script Features
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Reading Input File: Parses a text file containing usernames and group names.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;User Creation: Creates users with personal groups if they don't already exist.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Password Management: Generates and assigns random passwords to users.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Group Assignment: Adds users to specified groups.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Logging: Records all actions to a log file for auditing purposes.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Script
&lt;/h2&gt;

&lt;p&gt;Below is the create_users.sh script, broken down into detailed code blocks for better understanding.&lt;/p&gt;

&lt;p&gt;Reading the Input File&lt;br&gt;
The script begins by defining a function to read and parse the input file. Each line in the file contains a username and a list of groups separated by a semicolon (;).&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 read and parse the input file
read_input_file() {
  local filename="$1"
  while IFS=';' read -r user groups; do
    users+=("$(echo "$user" | xargs)")
    group_list+=("$(echo "$groups" | tr -d '[:space:]')")
  done &amp;lt; "$filename"
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Purpose: This function reads the input file line by line.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Parsing: Each line is split into user and groups using the semicolon (;) as a delimiter.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Trim Whitespace: The xargs command removes any leading or trailing whitespace from user, and tr -d '[:space:]' removes all spaces from groups.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Storing Data: Usernames are stored in the users array and group lists in the group_list array.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Creating a User with a Personal Group&lt;br&gt;
Next, we define a function to create a user and their personal group. If the user already exists, the script logs a message and skips the creation.&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 create a user with its personal group
create_user_with_group() {
  local username="$1"
  if id "$username" &amp;amp;&amp;gt;/dev/null; then
    echo "User $username already exists." | tee -a "$log_file"
  else
    groupadd "$username"
    useradd -m -g "$username" -s /bin/bash "$username"
    echo "Created user $username with personal group $username." | tee -a "$log_file"
  fi
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Check Existence: The id command checks if the user already exists. If they do, a message is logged.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create Group: If the user does not exist, the script creates a new group with the same name as the username using groupadd.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create User: The useradd command creates a new user with:&lt;br&gt;
  -m: Creates a home directory for the user.&lt;br&gt;
  -g "$username": Assigns the user to their personal group.&lt;br&gt;
  -s /bin/bash: Sets the default shell to /bin/bash.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Setting a Password for the User&lt;/p&gt;

&lt;p&gt;This function generates a random password for the user, sets it, and stores the password in a secure file.&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 set a password for the user
set_user_password() {
  local username="$1"
  local password=$(openssl rand -base64 12)
  echo "$username:$password" | chpasswd
  echo "$username,$password" &amp;gt;&amp;gt; "$password_file"
  echo "Password for $username set and stored." | tee -a "$log_file"
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Generate Password: The openssl rand -base64 12 command generates a random 12-character password.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Set Password: The chpasswd command sets the user's password.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Store Password: The username and password are appended to the password file for future reference.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Logging: A message is logged indicating that the password was set and stored.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Adding the User to Additional Groups&lt;/p&gt;

&lt;p&gt;The following function adds the user to the specified groups. If a group does not exist, it is created.&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 add user to additional groups
add_user_to_groups() {
  local username="$1"
  IFS=',' read -r -a groups &amp;lt;&amp;lt;&amp;lt; "$2"
  for group in "${groups[@]}"; do
    if ! getent group "$group" &amp;amp;&amp;gt;/dev/null; then
      groupadd "$group"
      echo "Group $group created." | tee -a "$log_file"
    fi
    usermod -aG "$group" "$username"
    echo "Added $username to group $group." | tee -a "$log_file"
  done
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Split Groups: The IFS=',' setting and read -r -a groups &amp;lt;&amp;lt;&amp;lt; "$2" command split the group list into an array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Check Group Existence: The getent group "$group" command checks if each group exists.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create Group: If a group does not exist, it is created using groupadd.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Add User to Group: The usermod -aG "$group" "$username" command adds the user to each group.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Logging: Messages are logged for group creation and user addition.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Main Script Execution&lt;br&gt;
The main part of the script checks for the input file argument, initializes variables, creates log and password files if they don't exist, and processes each user in the input file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Check for input file argument
if [[ $# -ne 1 ]]; then
  echo "Usage: $0 &amp;lt;input_file&amp;gt;"
  exit 1
fi

# Initialize variables
input_file="$1"
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"
declare -a users
declare -a group_list

# Create log and password files if they do not exist
mkdir -p /var/log /var/secure
touch "$log_file"
touch "$password_file"
chmod 600 "$password_file"

# Read input file
read_input_file "$input_file"

# Process each user
for ((i = 0; i &amp;lt; ${#users[@]}; i++)); do
  username="${users[i]}"
  user_groups="${group_list[i]}"

  if [[ "$username" == "" ]]; then
    continue  # Skip empty usernames
  fi

  create_user_with_group "$username"
  set_user_password "$username"
  add_user_to_groups "$username" "$user_groups"
done

echo "User creation and group assignment completed." | tee -a "$log_file"

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Input File Argument: Checks if an input file is provided as an argument. If not, it exits with a usage message.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Initialize Variables: Sets the input file, log file, and password file paths. Initializes arrays for users and groups.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create Log and Password Files: Creates the log and password files if they do not exist and sets appropriate permissions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Read Input File: Calls the read_input_file function to populate the users and group_list arrays.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Process Users: Loops through each user in the users array:&lt;br&gt;
    Skip Empty Usernames: Continues to the next iteration if the &lt;br&gt;
username is empty.&lt;br&gt;
    Create User and Group: Calls create_user_with_group to &lt;br&gt;
create the user and their personal group.&lt;br&gt;
    Set Password: Calls set_user_password to set and store the &lt;br&gt;
user's password.&lt;br&gt;
    Add to Groups: Calls add_user_to_groups to add the user to &lt;br&gt;
specified groups.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Completion Message: Logs a message indicating that user creation and group assignment are complete.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to Use the Script
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Prepare the Input File: Create a file named users.txt with the following format:
&lt;/li&gt;
&lt;/ul&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;ul&gt;
&lt;li&gt;Run the Script: Execute the script with the input file as an argument:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./create_users.sh users.txt

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Check Logs and Passwords: Review the log file at /var/log/user_management.log for actions taken and find user passwords in /var/secure/user_passwords.txt.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Benefits of Automation
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Efficiency: Automates repetitive tasks, freeing up time for more critical activities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Consistency: Ensures that user and group configurations are applied uniformly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Security: Randomly generated passwords enhance security, and storing them securely minimizes risks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Auditing: Detailed logging helps in tracking changes and troubleshooting.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Learn More
&lt;/h2&gt;

&lt;p&gt;If you're interested in advancing your career in tech, consider joining the HNG Internship program by visiting &lt;a href="https://hng.tech/internship"&gt;HNG internship&lt;/a&gt; or &lt;a href="https://hng.tech/premium"&gt;HNG Premium&lt;/a&gt;. It's an excellent opportunity to gain hands-on experience and learn from industry professionals.&lt;/p&gt;

&lt;p&gt;For those looking to hire top tech talent, &lt;a href="https://hng.tech/hire"&gt;HNG Hire&lt;/a&gt; connects you with skilled developers who have undergone rigorous training. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Automating user and group management tasks with a bash script can significantly improve efficiency and security in a Linux environment. By following the steps outlined in this article, you can streamline your onboarding process and ensure proper user management.&lt;/p&gt;

</description>
      <category>bash</category>
      <category>devops</category>
    </item>
    <item>
      <title>Automating User and Group Management on Linux with a Bash Script</title>
      <dc:creator>Olawale</dc:creator>
      <pubDate>Fri, 05 Jul 2024 07:31:20 +0000</pubDate>
      <link>https://forem.com/hellowale/automating-user-and-group-management-on-linux-with-a-bash-script-2dm5</link>
      <guid>https://forem.com/hellowale/automating-user-and-group-management-on-linux-with-a-bash-script-2dm5</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Managing users and groups on a Linux system can be daunting, especially when onboarding new employees. As a SysOps engineer, automating these tasks can save time and reduce errors. This article explores a bash script called create_users.sh that automates user creation, password management, and group assignments. This script reads from an input file and logs all actions, ensuring a smooth and auditable process.&lt;/p&gt;

&lt;h2&gt;
  
  
  Script Features
&lt;/h2&gt;

&lt;p&gt;Reading Input File: Parses a text file containing usernames and group names.&lt;br&gt;
User Creation: Creates users with personal groups if they don't already exist.&lt;br&gt;
Password Management: Generates and assigns random passwords to users.&lt;br&gt;
Group Assignment: Adds users to specified groups.&lt;br&gt;
Logging: Records all actions to a log file for auditing purposes.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Script
&lt;/h2&gt;

&lt;p&gt;Below is the create_users.sh script. Save this script to your server and make it executable.&lt;br&gt;
&lt;/p&gt;

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

# Function to read and parse the input file
read_input_file() {
  local filename="$1"
  while IFS=';' read -r user groups; do
    users+=("$(echo "$user" | xargs)")
    group_list+=("$(echo "$groups" | tr -d '[:space:]')")
  done &amp;lt; "$filename"
}

# Function to create a user with its group
create_user_with_group() {
  local username="$1"
  if id "$username" &amp;amp;&amp;gt;/dev/null; then
    echo "User $username already exists." | tee -a "$log_file"
  else
    groupadd "$username"
    useradd -m -g "$username" -s /bin/bash "$username"
    echo "Created user $username with personal group $username." | tee -a "$log_file"
  fi
}

# Function to set a password for the user
set_user_password() {
  local username="$1"
  local password=$(openssl rand -base64 12)
  echo "$username:$password" | chpasswd
  echo "$username,$password" &amp;gt;&amp;gt; "$password_file"
  echo "Password for $username set and stored." | tee -a "$log_file"
}

# Function to add users to additional groups
add_user_to_groups() {
  local username="$1"
  IFS=',' read -r -a groups &amp;lt;&amp;lt;&amp;lt; "$2"
  for group in "${groups[@]}"; do
    if ! getent group "$group" &amp;amp;&amp;gt;/dev/null; then
      groupadd "$group"
      echo "Group $group created." | tee -a "$log_file"
    fi
    usermod -aG "$group" "$username"
    echo "Added $username to group $group." | tee -a "$log_file"
  done
}

# Check for an input file argument
if [[ $# -ne 1 ]]; then
  echo "Usage: $0 &amp;lt;input_file&amp;gt;"
  exit 1
fi

# Initialize variables
input_file="$1"
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"
declare -a users
declare -a group_list

# Create log and password files if they do not exist
mkdir -p /var/log /var/secure
touch "$log_file"
touch "$password_file"
chmod 600 "$password_file"

# Read input file
read_input_file "$input_file"

# Process each user
for ((i = 0; i &amp;lt; ${#users[@]}; i++)); do
  username="${users[i]}"
  user_groups="${group_list[i]}"

  if [[ "$username" == "" ]]; then
    continue  # Skip empty usernames
  fi

  create_user_with_group "$username"
  set_user_password "$username"
  add_user_to_groups "$username" "$user_groups"
done

echo "User creation and group assignment completed." | tee -a "$log_file"

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to Use the Script
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Prepare the Input File: Create a file named users.txt with the following format:
&lt;/li&gt;
&lt;/ul&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;ul&gt;
&lt;li&gt;Reading the Input File&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The script begins by defining a function to read and parse the input file. Each line in the file contains a username and a list of groups separated by a semicolon (;).&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 read and parse the input file
read_input_file() {
  local filename="$1"
  while IFS=';' read -r user groups; do
    users+=("$(echo "$user" | xargs)")
    group_list+=("$(echo "$groups" | tr -d '[:space:]')")
  done &amp;lt; "$filename"
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Creating a User with a Personal Group&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Next, we define a function to create a user and their group. If the user already exists, the script logs a message and skips the creation.&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 create a user with its group
create_user_with_group() {
  local username="$1"
  if id "$username" &amp;amp;&amp;gt;/dev/null; then
    echo "User $username already exists." | tee -a "$log_file"
  else
    groupadd "$username"
    useradd -m -g "$username" -s /bin/bash "$username"
    echo "Created user $username with personal group $username." | tee -a "$log_file"
  fi
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Setting a Password for the User&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This function generates a random password for the user, sets it, and stores the password in a secure file.&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 set a password for the user
set_user_password() {
  local username="$1"
  local password=$(openssl rand -base64 12)
  echo "$username:$password" | chpasswd
  echo "$username,$password" &amp;gt;&amp;gt; "$password_file"
  echo "Password for $username set and stored." | tee -a "$log_file"
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Adding the User to Additional Groups&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following function adds the user to the specified groups. If a group does not exist, it is created.&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 add users to additional groups
add_user_to_groups() {
  local username="$1"
  IFS=',' read -r -a groups &amp;lt;&amp;lt;&amp;lt; "$2"
  for group in "${groups[@]}"; do
    if ! getent group "$group" &amp;amp;&amp;gt;/dev/null; then
      groupadd "$group"
      echo "Group $group created." | tee -a "$log_file"
    fi
    usermod -aG "$group" "$username"
    echo "Added $username to group $group." | tee -a "$log_file"
  done
}

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Main Script Execution&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The main part of the script checks for the input file argument initializes variables, creates log and password files if they don't exist, and processes each user in the input file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Check for an input file argument
if [[ $# -ne 1 ]]; then
  echo "Usage: $0 &amp;lt;input_file&amp;gt;"
  exit 1
fi

# Initialize variables
input_file="$1"
log_file="/var/log/user_management.log"
password_file="/var/secure/user_passwords.txt"
declare -a users
declare -a group_list

# Create log and password files if they do not exist
mkdir -p /var/log /var/secure
touch "$log_file"
touch "$password_file"
chmod 600 "$password_file"

# Read input file
read_input_file "$input_file"

# Process each user
for ((i = 0; i &amp;lt; ${#users[@]}; i++)); do
  username="${users[i]}"
  user_groups="${group_list[i]}"

  if [[ "$username" == "" ]]; then
    continue  # Skip empty usernames
  fi

  create_user_with_group "$username"
  set_user_password "$username"
  add_user_to_groups "$username" "$user_groups"
done

echo "User creation and group assignment completed." | tee -a "$log_file"

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

&lt;/div&gt;



&lt;p&gt;Run the Script: Execute the script with the input file as an argument:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./create_users.sh users.txt

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

&lt;/div&gt;



&lt;p&gt;Check Logs and Passwords: Review the log file at /var/log/user_management.log for actions taken and find user passwords in /var/secure/user_passwords.txt.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Automation
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Efficiency: Automates repetitive tasks, freeing time for more critical activities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Consistency: Ensures that user and group configurations are applied uniformly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Security: Randomly generated passwords enhance security, and storing them securely minimizes risks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Auditing: Detailed logging helps in tracking changes and troubleshooting.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Learn More
&lt;/h2&gt;

&lt;p&gt;If you're interested in advancing your career in tech, consider joining the HNG Internship program by visiting &lt;a href="https://hng.tech/internship"&gt;HNG Internship&lt;/a&gt; or &lt;a href="https://hng.tech/premium"&gt;HNG Premium&lt;/a&gt;. It's an excellent opportunity to gain hands-on experience and learn from industry professionals.&lt;/p&gt;

&lt;p&gt;For those looking to hire top tech talent, &lt;a href="https://hng.tech/hire"&gt;HNG Hire&lt;/a&gt;  connects you with skilled developers who have undergone rigorous training.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Automating user and group management tasks with a bash script can significantly improve efficiency and security in a Linux environment. By following the steps outlined in this article, you can streamline your onboarding process and ensure proper user management.&lt;/p&gt;

</description>
      <category>bash</category>
      <category>devops</category>
    </item>
    <item>
      <title>Automating User Management on Linux with Bash Scripting</title>
      <dc:creator>Olawale</dc:creator>
      <pubDate>Wed, 03 Jul 2024 09:21:38 +0000</pubDate>
      <link>https://forem.com/hellowale/automating-user-management-on-linux-with-bash-scripting-1jk1</link>
      <guid>https://forem.com/hellowale/automating-user-management-on-linux-with-bash-scripting-1jk1</guid>
      <description>&lt;p&gt;As a SysOps engineer, efficient user management is crucial for maintaining system security and functionality. I've developed a bash script called create_users.sh that automates user creation, password management, group assignment, and logging on Linux systems to simplify this process. This script is designed to dynamically handle multiple users and groups from a structured input file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Script Overview
&lt;/h2&gt;

&lt;p&gt;The create_users.sh script performs the following tasks:&lt;/p&gt;

&lt;p&gt;Reading Input: It reads from an input file (users.txt), where each line contains a username and associated groups separated by semicolons (username;group1,group2).&lt;/p&gt;

&lt;p&gt;User Creation: Checks if each user exists; if not, creates the user with a personal group (same name as the username).&lt;/p&gt;

&lt;p&gt;Password Management: Generates a random password for each user and securely stores it in /var/secure/user_passwords.txt.&lt;/p&gt;

&lt;p&gt;Group Management: Adds users to their group and optionally to additional groups specified in the input file.&lt;/p&gt;

&lt;p&gt;Logging: Records all actions in /var/log/user_management.log for audit purposes.&lt;/p&gt;

&lt;p&gt;Error Handling: Skips invalid lines and manages existing users gracefully.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Using This Script
&lt;/h2&gt;

&lt;p&gt;Efficiency: Automates tedious user management tasks, reducing manual errors and saving time.&lt;br&gt;
Security: Ensures passwords are generated securely and stored in a protected file.&lt;br&gt;
Flexibility: Handles varying user and group configurations dynamically from a single input file.&lt;br&gt;
Auditability: Logs every action performed, providing accountability and traceability.&lt;br&gt;
Usage Instructions&lt;br&gt;
To utilize the script:&lt;/p&gt;

&lt;p&gt;Ensure the users.txt file is formatted correctly with each line containing username; and groups.&lt;br&gt;
Run the script with ./create_users.sh users.txt on your Linux machine.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Automating user management tasks is essential for maintaining system integrity and security. The create_users.sh script simplifies these tasks by leveraging bash scripting capabilities. It ensures consistency, security, and efficiency in managing users and groups on Linux systems.&lt;/p&gt;

&lt;p&gt;For those interested in exploring system operations and infrastructure management opportunities, I recommend checking out the &lt;a href="https://hng.tech/internship"&gt;HNG Internship&lt;/a&gt; program. It offers valuable insights and practical experience in the tech industry, preparing aspiring professionals for rewarding careers.&lt;/p&gt;

&lt;p&gt;Additionally, you can learn more about opportunities at &lt;a href="https://hng.tech/premium"&gt;HNG Premium&lt;/a&gt;, which provides advanced training and mentorship for tech enthusiasts looking to accelerate their career growth.&lt;/p&gt;

&lt;p&gt;Feel free to access the script on GitHub and adapt it to suit your system's specific requirements.&lt;/p&gt;

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