Step-by-Step Guide to Automating Password Generation on Linux Using Bash

In this article, I will tell you how to use bash scripts to automatically generate passwords for new user accounts on a Linux system.

Scenario: The support staff warmly accepted the script”add-local-user.sh“, appreciating the significant speed and efficiency it provides when creating accounts. In turn, they advised how the process could be improved: add an automatic password generation feature to improve security and eliminate repetitive tasks, and implement the ability to enter account names and comments directly from the command line to complete operations even faster. These changes not only streamline the team's workflow, but also improve overall company safety and efficiency.

Script requirements:

  • It is called “add-new-local-user.sh“. (We'll add the word new to the title to differentiate it from the original script we worked on in the previous part.)

  • Ensures that it is executed with superuser (root) rights. If the script is executed without root privileges, it will not even attempt to create a user, but will return an exit code of 1.

  • Provides a usage report similar to what can be found in the man page if the user does not specify an account name on the command line, and returns an exit code of 1.

  • Uses the first argument given on the command line as the username for the account. All other arguments on the command line will be treated as a comment to the account.

  • Automatically generates a password for a new account.

  • Informs the user if for some reason the account could not be created. If the account is not created, the script should return exit code 1.

  • Displays the username, password, and host where the account was created. This way, support staff can copy the results of the script, making it easier to provide information to the new account owner.

What you will need:

Step 1: Create a text file for the script

  • Create a new text file on the command line containing the script we will be working on.

  • Name the script “add-new-local-user.sh“.

touch add-new-local-user.sh

Step 2: Change Permissions to Gain Privileges to Run Executable Files

  • By default, Linux security does not allow files to be executed without the appropriate permissions. File permissions can be changed using the command “chmod“, followed by the corresponding numeric designations.

For example: chmod 755 or chmod 777

  • For the script we will be working on, we will specify the resolution as “755”.

chmod 755 add-new-local-user.sh

Step 3: Create a script

  • To designate a text file as a script, the first thing you need to do is start the first line with a shebang. Shebang lets the interpreter know how to execute the file.

  • The first task of the script is to ensure that it is executed with superuser privileges.

  • The portion of the script you see below instructs the user at the command line to execute the script as sudo or root. Without superuser privileges, the script will not work properly.

User information section:

Our goal is for the user (support staff) to enter an account name and the script will automatically generate a random password for it. Each user will receive their own unique password, which will save us from having to manually create a password for each new user on a Linux system.

  • USER_NAME="$1": This line stores the first argument passed to the script in a variable USER_NAME. When you run the script, you provide the name of the new user as this first argument.

  • shift: This command shifts the script's argument list so that the second argument becomes the first, the third becomes the second, and so on. It is used here because everything else after the first argument is considered comments to the account.

  • COMMENT="$@": After shift represents all remaining command line arguments that are assigned to the variable COMMENT. They are used as a comment for the user account.

  • PASSWORD=$(date +%s%N | sha256sum | head -c48): This line generates a password by taking the current date and time in nanoseconds and running it through the command sha256sum to create a hash and then using head -c48 to get its first 48 characters.

  • useradd -c "${COMMENT}" -m ${USER_NAME}: Team useradd used to create a new user with a comment specified in a variable COMMENTand the username specified in the variable USER_NAME. Parameter -m creates the user's root directory.

  • if [[ "${?}" -ne 0 ]]: Checks the exit code of the last command (in this case useradd). is a special variable that stores the exit status of the last executed command. -ne 0 checks to see if this code is 0, which means an error occurred.

  • echo 'The account could not be created.': If the user creation command fails (i.e. the condition if true), this line will display a message stating that the account could not be created.

  • exit 1: Exits the script and returns code 1, which usually indicates that an error occurred.

Password generation section:

  • echo ${PASSWORD} | passwd – stdin ${USER_NAME}: Sets the password for the new user that was entered as the first argument. Once the user has been assigned a password, it will be displayed on the command line. The password will be passed to the passwd command, which will change the password based on the username.

  • Next operator if checks if the command was passwd successful, looking at the exit code ($?). If the code is not 0 (meaning an error occurred), it prints “The password for the account could not be set.” and exits the script with an exit code of 1, indicating an error.

  • passwd -e ${USER_NAME}: This command forces the new user to change the password the next time they log in for security purposes.

  • Teams echo displays the username, the generated password, and the host (computer name) on which the user was created. This information is printed to the terminal so that the person running the script can save the new account details somewhere.

  • exit 0: The script exits with an exit code of 0, which indicates success.

The entire script:

Step 4: Checking the Script

Now we'll test our script and see how it works!

  • Enter your username to see if a password will be generated.

  • Be sure to copy one of the passwords and save it somewhere. We will change it to a new unique password.

sudo ./add-new-local.user.sh exampleuser COMMENT
Ex: sudo ./add-new-local.user.sh gbaidoo George Baidoo
Success

Success

User #2

Success

Success

User #3

Success

Success

If you get results similar to those seen in the images above, then the script is working correctly. Great job!

Try running the script without sudo or root privileges.

  • Remember that we wrote the script so that only a user with permissions can execute it sudo or root. If you try to execute this file without the appropriate rights, you will be denied access and prompted to run the script with sudo.

Replace the randomly generated password with a unique one

  • Let's change the password of one of your users by running the “su” command with the username.

  • Paste the generated password into the “current password” section and press Enter.

  • Enter the new password twice to confirm the change.

su - example
Ex: su - gbaidoo

Congratulations, if you've made it this far, you've successfully completed this project! You learned how to write a script that automatically generates passwords for new users on a Linux system, demonstrating the efficiency and security of Linux system administration!


This evening there will be an open lesson “Angie Web Server: Comparison with Nginx, New Features.” The lesson will be useful for Linux system administrators, web developers and anyone who uses Nginx in their projects. Sign up link.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *