<?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: Adeshile Osunkoya</title>
    <description>The latest articles on DEV Community by Adeshile Osunkoya (@adeshile_osunkoya_4201f36).</description>
    <link>https://dev.to/adeshile_osunkoya_4201f36</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%2F1713566%2F91660234-349e-45b0-8823-ff51f4087bcd.png</url>
      <title>DEV Community: Adeshile Osunkoya</title>
      <link>https://dev.to/adeshile_osunkoya_4201f36</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/adeshile_osunkoya_4201f36"/>
    <language>en</language>
    <item>
      <title>Creating and Managing Users and Groups on Linux with Bash Scripts: An Efficient Guide 🚀🐧</title>
      <dc:creator>Adeshile Osunkoya</dc:creator>
      <pubDate>Fri, 05 Jul 2024 03:38:01 +0000</pubDate>
      <link>https://dev.to/adeshile_osunkoya_4201f36/creating-and-managing-users-and-groups-on-linux-with-bash-scripts-an-efficient-guide-2pog</link>
      <guid>https://dev.to/adeshile_osunkoya_4201f36/creating-and-managing-users-and-groups-on-linux-with-bash-scripts-an-efficient-guide-2pog</guid>
      <description>&lt;p&gt;Welcome to Linux user management! In a growing organization, manually managing user accounts and groups can quickly become tedious and error-prone. To streamline this process and maintain security and productivity, automation is key. 🛠️💪&lt;/p&gt;

&lt;p&gt;With a Bash script, you can automate the repetitive tasks of creating and managing users and groups, ensuring consistency and efficiency while saving countless hours and reducing the risk of errors.&lt;/p&gt;

&lt;p&gt;In this article, we’ll show you how to create a script to automate the user and group creation process—a common task for any SysOps engineer. Let's dive in and simplify your workflow! 🌟&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Prerequisites&lt;/strong&gt;
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Linux or Ubuntu running on either VM (Virtual box), Docker, AWS Ec2 instance.&lt;/li&gt;
&lt;li&gt;Basic knowledge of Linux commands and Bash scripting.&lt;/li&gt;
&lt;li&gt;Root privileges to execute the script.&lt;/li&gt;
&lt;li&gt;Basic understanding of shell scripting and user management in Linux&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create user file&lt;/strong&gt; &lt;br&gt;
Create a &lt;code&gt;.txt&lt;/code&gt;file where your users will be listed and the groups they should be added to. A simple and easy to read file will be recommended. For this article , a sample file &lt;code&gt;user.txt&lt;/code&gt; has been created and will be formatted as &lt;code&gt;user;groups&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Gabriel;sudo,dev,www-data
Sultan;sudo
Chelsea;dev,www-data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line in the example above &lt;code&gt;Gabriel&lt;/code&gt; is the user and groups are &lt;code&gt;sudo, dev, www-data&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Create script file&lt;/strong&gt; &lt;br&gt;
Open your code editor and create a file e.g &lt;code&gt;create_users.sh&lt;/code&gt;, this can also be created in your root directory using your terminal by running:&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;&lt;em&gt;NB: The script file created will handle the logic of the user and group in&lt;/em&gt; &lt;strong&gt;Step 1&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Script implementation&lt;/strong&gt;&lt;br&gt;
First we need to check the administrative priviledge of the script user.&lt;/p&gt;

&lt;p&gt;Check if the first argument is passed: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The script begins with a shebang line and a check for root privileges to ensure the necessary permissions for user and group management.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#!/bin/bash
 if (( "$UID != 0" ))
then
    echo "Error: script requires root privilege"
exit 1
fi

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

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Shebang (#!/bin/bash)&lt;/strong&gt;: Indicates that the script should be run in the Bash shell.&lt;br&gt;
&lt;strong&gt;Root Privileges Check&lt;/strong&gt;: Verifies if the script is executed by the root user. If not, it prints an error and exits.&lt;/p&gt;

&lt;p&gt;Then , the script processes input arguments and checks for the presence and type of the file &lt;code&gt;(text/plain)&lt;/code&gt; containing user data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Save all arguments in an array
ARGS=("$@")

# Check whether no arguments are supplied
if [ "$#" -eq 0 ]; then
    echo "No arguments supplied"
    exit 1
fi

# Define a variable for the file
FILE=${ARGS[0]}

# Check if the file exists
if [ ! -f "$FILE" ]; then
    echo "Error: File $FILE does not exist."
    exit 1
fi

# Get the MIME type and check if it is text/plain
file_type=$(file -b --mime-type "$FILE")
if [[ "$file_type" != "text/plain" ]]; then
    echo "Error: required file type is not text/plain"
    exit 1 
fi

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Argument Handling&lt;/strong&gt;: Captures script arguments and checks if any are provided.&lt;br&gt;
&lt;strong&gt;File Existence Check&lt;/strong&gt;: Verifies if the specified file exists.&lt;br&gt;
&lt;strong&gt;MIME Type Check&lt;/strong&gt;: Ensures the file is a plain text file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Logging and Data Writing Functions&lt;/strong&gt;&lt;br&gt;
I used this function below to log all actions by logging all user actions into &lt;code&gt;/var/log/user_management.log&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;# Logging and writing data
log() {
    sudo printf "$*\n" &amp;gt;&amp;gt; $log_path
}

# Function to save user data
user_data() {
    sudo printf "$1,$2\n" &amp;gt;&amp;gt; $3
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Generate Random Passwords&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;genpasswd&lt;/code&gt; function is used to generate a secure random password of specified length (default 16 characters)for the user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;genpasswd() { 
    local l=$1
        [ "$l" == "" ] &amp;amp;&amp;amp; l=16
        tr -dc A-Za-z0-9_ &amp;lt; /dev/urandom | head -c ${l} | xargs 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Process Each Line in the users.txt file:&lt;/strong&gt; &lt;br&gt;
The below code block will read each line of &lt;code&gt;users.txt&lt;/code&gt; file and get the &lt;code&gt;username&lt;/code&gt; and &lt;code&gt;user groups&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;# Create user function

    create_user(){
        username="$1"
        password=$(genpasswd)
 # If username exists, do nothing
    if [ ! $(cat /etc/passwd | grep -w $username) ]; then

        # User is created with a group as their name
        sudo useradd -m -s /bin/bash $username
 # Set the user's password
        echo "$username:$password" | sudo chpasswd
        msg="User '$username' created with the password '********'"
        echo $msg
        log $msg

       # Save user data
        dir=/home/$username/$user_pass
        create_file_directory $dir
        user_data $username $password $dir

         # Set file group to user and give read only access
        sudo chgrp $username $dir
        sudo chmod 640 $dir
    fi

    }

create_group() {
    # Create group
    # If group exists, do nothing
    if [ ! $(cat /etc/group | grep -w $1) ]; then
        sudo groupadd $1
        msg="Group created '$1'"
        echo $msg
        log $msg
    fi
}

 #  Add user to group
    add_user_to_group() {

   sudo usermod -aG $2 $1
   msg="'$1' added to '$2'"
   echo $msg
   log $msg
}

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

&lt;/div&gt;



&lt;p&gt;The code block above contains the following functions: &lt;br&gt;
&lt;code&gt;create_user Function&lt;/code&gt;: Creates a user with a home directory and sets the password.&lt;br&gt;
&lt;code&gt;create_group Function&lt;/code&gt;: Creates a group if it doesn’t already exist.&lt;br&gt;
&lt;code&gt;add_user_to_group Function&lt;/code&gt;: Adds a user to a specified group.&lt;/p&gt;

&lt;p&gt;The user and password is created and then the details are then stored in the user directory using the below path: &lt;br&gt;
&lt;code&gt;[user home directory]/var/secure/user_passwords.txt&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The user data reads file and creates users and groups accordingly.&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 FILE
while IFS= read -r line || [ -n "$line" ]; do
    username=$(printf "%s" "$line" | cut -d ';' -f 1)
    echo "----- Process started for: '$username' -----"
    create_user $username
    usergroups=$(printf "%s" "$line" | cut -d ';' -f 2)
    for group in ${usergroups//,/ } ; do 
        create_group $group
        add_user_to_group $username $group
    done
    echo "----- Process Done with '$username' -----"
done &amp;lt; $FILE

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Run script file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's time to test our script to ensure that our code is working.&lt;/p&gt;

&lt;p&gt;Run the &lt;code&gt;.txt&lt;/code&gt; file by using the command below on your terminal.&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;The below result should be displayed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;File and path created: /var/log/user_management.log
----- Process started for: 'Gabriel' -----
User 'Gabriel' created with the password '********'
File and path created: /home/Gabriel/var/secure/user_passwords.txt
'Gabriel' added to 'sudo'
'Gabriel' added to 'dev'
'Gabriel' added to 'www-data'
----- Process Done with 'Gabriel' -----
----- Process started for: 'Sultan' -----
User 'Sultan' created with the password '********'
File and path created: /home/Sultan/var/secure/user_passwords.txt
'Sultan' added to 'sudo'
----- Process Done with 'Sultan' -----
----- Process started for: 'Chelsea' -----
User 'Chelsea' created with the password '********'
File and path created: /home/Chelsea/var/secure/user_passwords.txt
'Chelsea' added to 'dev'
'Chelsea' added to 'www-data'
----- Process Done with 'Chelsea' -----
root@32cb601ed360:~# cat /home/Gabriel/var/secure/user_passwords.txt
Gabriel,yDEoSe1RfzIwxmhk
root@32cb601ed360:~# bash create.users.sh users.txt
File and path created: /var/log/user_management.log
----- Process started for: 'Gabriel' -----
'Gabriel' added to 'sudo'
'Gabriel' added to 'dev'
'Gabriel' added to 'www-data'
----- Process Done with 'Gabriel' -----
----- Process started for: 'Sultan' -----
'Sultan' added to 'sudo'
----- Process Done with 'Sultan' -----
----- Process started for: 'Chelsea' -----
'Chelsea' added to 'dev'
'Chelsea' added to 'www-data'
----- Process Done with 'Chelsea' -----
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To see all groups created run:&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;sudo cat /etc/group
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To see all users and groups they belong run:&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;sudo cat /etc/passwd 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;My full code implementation can be found on Github: &lt;a href="https://github.com/Adeshile2/user-manage-bash"&gt;Creating and Managing Users&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;HNG Internships&lt;/strong&gt;&lt;br&gt;
For more information about the HNG Internship, visit [HNG Internship (&lt;a href="https://hng.tech/internship"&gt;https://hng.tech/internship&lt;/a&gt;) and if you want to hire world class freelancers and developers , check: &lt;a href="//hng.tech/hire"&gt;HNG Hire&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks for reading through please do ensure to leave feedback so as to better serve my reader 😊&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
This Bash script automates the process of creating and managing users and groups on a Linux system, making it easier to maintain consistency and security across your user base. By following this guide, you can efficiently manage user accounts and group memberships with minimal manual effort.&lt;/p&gt;

</description>
      <category>devops</category>
      <category>cloudcomputing</category>
      <category>ubuntu</category>
      <category>bash</category>
    </item>
  </channel>
</rss>
