BASH: Create User Accounts with Random Password

Generally, adding a single user in Linux is pretty straight forward and easy to do. Passwords may be set by the administrator or randomly generated by going out to random.org or passwordgenerator.net.

Pass a UserID to this script and it will create it with a random password. Password complexity and length can be changed within the script.

I am going to break the script down line by line below.

Writing the script

We are going to write a basic BASH script that will take variables on the command line and create a user with a random password.

Using your favorite text editor such as vi/emacs, open a blank file.

Let’s begin writing some code and I’ll explain afterwards what is going on.

The first line, calls the executable that will be used to interpret the script. In this instance, we are calling bash since we are going to write the code in such a way that bash understands it. In addition, add a banner to help remember why this script was created to begin with.

Declare Variables

Assigning values to variables is much easier to work with and keeps the code much cleaner.

In the first line, we are assigning the $1 variable to “newuser”. $1 variable was created and declared when an argument was passed to the script. If you were to pass a second argument to the script, that would automatically be contained in $2 and so on.

The real engine behind this script is creating the random password. Within this, we run a command then assign it to the “randompw” variable.

The command breaks down as such:

urandom is a special file that serves as a random character or number generator. In summary, the randomness comes from the noise created by various device drivers within the operating system. The purpose of this is to take these random characters and begin slicing and dicing them into a password. From here we will use the ‘|’ to redirect the output into another command.

Using tr or translate with the -dc switch, we are removing all characters except for what is specified in the first set. In this particular example, we are going to remove any characters that are not “a-z” (lowercase characters), “A-Z” (upper case characters) and “0-9” (all numbers). This is an important step because many of the random characters are not printable and running this command out to your terminal may even disconnect your session.

Mix in special characters into the password by adding them to the filter set.

Up until this point, we have taken a stream of characters and removed any characters that do not fall into the template we created with the tr command. Now it is time to cut that string into the length of the password. Using the fold command with the width (-w) option, we are going to specify that each password is 8 characters long. Of course you can change this in your script as well. If you wanted to get super fancy, you could make the width number an argument passed into your script.

Imagine we started mining for gold and we filled our cart up with mixture of raw ore and other rocks with urandom. We refined that down to just gold using our tr command. Now we need a portable way to carry the told so we mint them into individual bars using fold. Next, I want to take the top bar off of the stack, that’s what the command head will do for us.

The head command will print the first number of lines specified in the -n option. In this case, 1.

Now that the new password has been created, it is now assigned to the variable randompw.

Create New User and Assign Password

In the next portion of code, the script will use our variables we declared earlier to create the new user and assign it the random password.

Useradd will add a user to the operating system with a home directory, mail box and no password.

Chpasswd is a command commonly used for changing user passwords on Unix/Linux operating systems. It has the ability to take in values from standard input (stdin) in the form of username:password. In this case, we are specifying the $newuser and $randompw variable as a stream of input to chpasswd command.

We want to let the administrator know that the script is complete and what the password is.

Optional

We are going to insert some logic which will stop the script from executing in the event that no user name is supplied as an argument. This step is optional, but add some polish to the final product.

This is a block of code which performs an evaluation on a boolean expression (meaning that the resulting evaluation will be true or false), and act accordingly.

An if .. then statement is the top line of the block and the bottom line of the block. Conditionals like this one are the buns of the block, and the meat gets stuffed in the middle. What it is saying that “if this statement is true, then let’s do this” until we reach “fi”, ending the conditional.

The evaluation occurs between the brackets. We are evaluating “$# -lt 1”. $# is the number of arguments passed when the script is run.

The next portion of the evaluation is “-lt”, which means less than. We are evaluating that the number of arguments is less than 1.

Let’s read the first line in pseudo code like this:

Inside the If then statement, we have 3 lines. The first two will “echo” whatever is inside the quotes back to the terminal which executed the script (also known as “Standard Output” or stdout). The exit command will terminate the script.

The second line concatenates a string “Example: ” followed by a $0, then ends with another string “jsmith”. The $0 would print the script’s name to the screen. This is useful if you like renaming your scripts and would keep the messages consistent.

Conclusion

This script can be changed and tweaked to perform this for multiple users. I urge you to toy around with it and try new things.

2 Replies to “BASH: Create User Accounts with Random Password”

  1. The best in class, Depoxito have enough money you high-end
    experience that adopt the see and setting of authentic
    VIP standarts, we have the funds for you the best captivating to
    high-level experience of VIPs expect in any summit end
    casino, grand living casino royale have enough money you the supplementary
    studio design element including the grand blackjack, offering our VIP Customer the best experience of a Salon privee table.

    New style table with feature across the room considering grand roulette
    upgraded on our provider playtechs mini prestige roulette which delivering more interesting and richer playing
    experience. The extra experience contains a sum of seven tables including five blackjack tables, one roulette table and one baccarat table.
    Grand enliven casino royale has been tall hand-engineered
    to fit the needs of our customer to using it, and contains unique elements that is specially meant
    to maximize the impact value we got from our customers and diversify it to the existing
    network.
    Soon, Depoxito will fabricate an enlarged truth technology on stimulate casino for our VIP member, these
    most ahead of its time technology ever seen in conscious casino including this greater than before reality.

    Which permit players to experience products on an entire
    additional level which is never seen past literally leaping out of the game and taking the blackjack,
    baccarat, roulette and further game into the amass entire level.

    Depoxito VIP Baccarat, we provide you the unquestionably exclusive liven up VIP
    Baccarat that is played like taking place to 7 players at the same table and our extremely trained pretty living baccarat dealer.
    And of course our VIP supporter will mood as if they were in reality sitting
    at one of the top casino baccarat table. This immersive gaming
    experience creates a hugely carefree express that our
    VIP players will locate hard to surpass.
    Here is the list of living casino game that depoxito
    provide, we have enough money the widest range of living casino games upon the publicize including : blackjack unlimited,
    blackjack prestige, roulette, baccarat, poker, hi-lo, sic bo, and grand rouse
    casino royale such as Grand Baccarat, Grand Blackjack and
    Grand Roulette for our VIP member. And of course
    as a believer of Depoxito you can enjoy every the games
    that we come up with the money for to you, every you compulsion to pull off is just visit our site depoxito and register it lonesome takes going
    on to 3 minutes and subsequently youre usual to accomplish any game that you want.

    Be our VIP, brute our VIP advocate of course fixed you the best facilitate you can acquire
    from us all you habit to be a VIP enthusiast is no question easy.
    every you craving is just keep playing upon our site,
    lump and comport yourself in imitation of a VIP following the amount that our company had written, keep playing and our
    customer promote will retrieve you that you are
    promoted to become a VIP aficionada upon our site.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.