<?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: Segun Moses</title>
    <description>The latest articles on DEV Community by Segun Moses (@by_segun_moses).</description>
    <link>https://dev.to/by_segun_moses</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%2F1714870%2F54b0a205-cbbc-4cfb-a6b9-e775b50ae5d3.jpg</url>
      <title>DEV Community: Segun Moses</title>
      <link>https://dev.to/by_segun_moses</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/by_segun_moses"/>
    <language>en</language>
    <item>
      <title>Automating Linux User Management with Bash Scripting</title>
      <dc:creator>Segun Moses</dc:creator>
      <pubDate>Tue, 02 Jul 2024 03:44:11 +0000</pubDate>
      <link>https://dev.to/by_segun_moses/automating-linux-user-management-with-bash-scripting-3f8d</link>
      <guid>https://dev.to/by_segun_moses/automating-linux-user-management-with-bash-scripting-3f8d</guid>
      <description>&lt;p&gt;Managing user accounts on a Linux system can be daunting, especially in environments with frequent employee onboarding. As a DevOps engineer, familiar with operational SysOps functionalities, I often need a reliable, automated solution to streamline this process. This is where the &lt;em&gt;create_users.sh&lt;/em&gt; Bash script comes into play, automating user creation and management based on input from a text file.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;The Script’s Mission&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The primary goal of create_users.sh is to automate the creation of user accounts on a Linux machine. Reading a specified text file containing usernames and associated groups, the script performs a series of operations to ensure each user is set up correctly with appropriate permissions and group memberships.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step-by-Step Explanation&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Write your create_users.sh file (touch create_users.sh)
**&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Create a new script file named create_users.sh with the necessary permissions using the commands&lt;/p&gt;

&lt;p&gt;I.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;II.&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;/p&gt;

&lt;ol&gt;
&lt;li&gt;Check for Input File
**&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Before proceeding, the script verifies that you’ve provided an input file containing user and group information. This early check prevents errors and guides users on proper script usage. Create a text file sample user and group data sudo nano user_data.txt&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

# Log file location
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Check if the input file is provided
if [ -z "$1" ]; then
  echo "Error: No file was provided"
  echo "Usage: $0 &amp;lt;name-of-text-file&amp;gt;"
  exit 1
fi

# Create log and password files
mkdir -p /var/secure
touch $LOGFILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

generate_random_password() {
    local length=${1:-10} # Default length is 10 if no argument is provided
    LC_ALL=C tr -dc 'A-Za-z0-9!?%+=' &amp;lt; /dev/urandom | head -c $length
}

# Function to create a user
create_user() {
  local username=$1
  local groups=$2

  if getent passwd "$username" &amp;gt; /dev/null; then
    echo "User $username already exists" | tee -a $LOGFILE
  else
    useradd -m $username
    echo "Created user $username" | tee -a $LOGFILE
  fi

  # Add user to specified groupsgroup
  groups_array=($(echo $groups | tr "," "\n"))

  for group in "${groups_array[@]}"; do
    if ! getent group "$group" &amp;gt;/dev/null; then
      groupadd "$group"
      echo "Created group $group" | tee -a $LOGFILE      
    fi
    usermod -aG "$group" "$username"
    echo "Added user $username to group $group" | tee -a $LOGFILE
  done

  # Set up home directory permissions
  chmod 700 /home/$username
  chown $username:$username /home/$username
  echo "Set up home directory for user $username" | tee -a $LOGFILE

  # Generate a random password
  password=$(generate_random_password 12) 
  echo "$username:$password" | chpasswd
  echo "$username,$password" &amp;gt;&amp;gt; $PASSWORD_FILE
  echo "Set password for user $username" | tee -a $LOGFILE
}

# Read the input file and create users
while IFS=';' read -r username groups; do
  create_user "$username" "$groups"
done &amp;lt; "$1"

echo "User creation process completed." | tee -a $LOGFILE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Define Variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Key variables such as &lt;code&gt;INPUT_FILE&lt;/code&gt;, &lt;code&gt;LOG_FILE&lt;/code&gt;, and &lt;code&gt;PASSWORD_FILE&lt;/code&gt; are defined to manage paths and filenames throughout the script. This enhances readability and makes maintenance easier.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Create Directories and Secure Password File&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ensuring security is paramount. The script creates necessary directories if they don’t exist and initializes a password file (/var/secure/user_passwords.csv) with stringent permissions (&lt;code&gt;chmod 600&lt;/code&gt;). This ensures that only authorized users can access sensitive password information.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Define Functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Modularity is key to maintainable scripting. The script defines two functions:&lt;/p&gt;

&lt;p&gt;generate_password(): Utilizes OpenSSL to generate strong, random passwords for each user.&lt;br&gt;
log_message(): Logs detailed actions and timestamps into LOG_FILE, facilitating troubleshooting and audit trails.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Read and Process Input File&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The heart of the script lies in processing the input file:&lt;/p&gt;

&lt;p&gt;It reads each line, compiles formatting, and parses usernames and associated groups.&lt;br&gt;
For each user:&lt;br&gt;
It checks if the user already exists to prevent duplication.&lt;br&gt;
If not, it creates the user with their primary group and creates a secure home directory.&lt;br&gt;
A random password is generated and securely stored in &lt;code&gt;PASSWORD_FILE&lt;/code&gt;.&lt;br&gt;
Additional specified groups are created if needed, and the user is added to these groups.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. End of Script&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Upon completion, the script logs a message indicating successful user creation and prompts users to review the &lt;code&gt;LOG_FILE&lt;/code&gt; for detailed operations performed.&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%2F2mufdkvgsp5yfymnmgnv.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%2F2mufdkvgsp5yfymnmgnv.png" alt="Image description" width="800" height="496"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Important Decisions&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Password Security&lt;/strong&gt;: Emphasizing security, the script employs OpenSSL to generate robust passwords. Storing passwords in a file with restricted permissions (600) ensures compliance with security best practices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Logging&lt;/strong&gt;: Detailed logging (log_message()) aids in troubleshooting and provides an audit trail of script activities. This proves invaluable in diagnosing issues and maintaining accountability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Error Handling&lt;/strong&gt;: The script anticipates potential errors, such as missing input files or existing user accounts, and handles them gracefully to prevent disruptions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Modular Functions&lt;/strong&gt;: The script promotes code reuse and maintainability by encapsulating password generation and logging into functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Group Management&lt;/strong&gt;: Dynamic group management ensures users are assigned to appropriate groups, enhancing system organization and access control.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  Real-World Application
&lt;/h2&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;p&gt;During my transformative journey with the &lt;a href="https://hng.tech/internship"&gt;HNG Internship&lt;/a&gt;, an immersive platform renowned for nurturing tech talents, I look towards encountering multifaceted challenges necessitating agile solutions. From creating seamless user provisioning amidst project expansions to fortifying data security protocols across distributed environments, the create_users.sh script emerged as a pivotal solution to overhead and task overload.&lt;/p&gt;

&lt;p&gt;To explore how the &lt;a href="https://hng.tech/internship"&gt;HNG Internship&lt;/a&gt; empowers emerging tech professionals, check out their comprehensive programs such as &lt;a href="https://hng.tech/internship"&gt;HNG Internship&lt;/a&gt;  and &lt;a href="https://hng.tech/hire"&gt;HNG Hire&lt;/a&gt;, known for industry excellence and transformative learning experiences.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>linux</category>
      <category>bash</category>
      <category>scripting</category>
    </item>
  </channel>
</rss>
