DEV Community

loading...
Cover image for Bash random password generator

Bash random password generator

Alex Georgiev
404 bio not found
Originally published at devdojo.com on ・4 min read

Introduction

It's a not an uncommon situation where you will need to generate a random password that you can use for any software installation or when you sign-up to any website.

There are a lot of options in order to achieve this. You can use a password manager/vault where you often have the option to randomly generate a password or to use a website that can generate the password on your behalf.

You can also use Bash in your terminal (command-line) to generate a password that you can quickly use. There are a lot of ways to achieve that and I will make sure to cover a few of them and will leave it up to you to choose which option is most suitable for your needs.

⚠️ Security

This script is intended to practice your bash scripting skills. You can have fun while doing simple projects with BASH, but security is not a joke, so please make sure you do not save your passwords in plain text in a local file or write them down by hand on a piece of paper.

I will highly recommend everyone to use secure and trusted providers to generate and save the passwords.

Script summary

Let me first do a quick summary of what our script is going to do.:

  1. We will have to option to choose the password characters length when the script is executed.
  2. The script will then generate 5 random passwords with the length that was specified in step 1

Prerequisites

You would need a bash terminal and a text editor. You can use any text editor like vi, vim, nano or Visual Studio Code.

I'm running the script locally on my Linux laptop but if you're using Windows PC you can ssh to any server of your choice and execute the script there.

Generate a random password

One of the great benefits of Linux is that you can do a lot of things using different methods. When it comes to generating a random string of characters it's no different as well.

You can use several commands in order to generate a random string of characters. I will cover a few of them and will provide some examples.

  • Using the date command. The date command will output the current date and time. However we also further manipulate the output in order to use it as a randomly generated password. We can hash the date using md5, sha or just run it through base64. These are a few examples:
date | md5sum
94cb1cdecfed0699e2d98acd9a7b8f6d  -
Enter fullscreen mode Exit fullscreen mode

using sha256sum:

date | sha256sum
30a0c6091e194c8c7785f0d7bb6e1eac9b76c0528f02213d1b6a5fbcc76ceff4  -
Enter fullscreen mode Exit fullscreen mode

using base64:

date | base64
0YHQsSDRj9C90YMgMzAgMTk6NTE6NDggRUVUIDIwMjEK
Enter fullscreen mode Exit fullscreen mode
  • We can also use openssl in order to generate pseudo-random bytes and run the output through base64. An example output will be:
openssl rand -base64 10
9+soM9bt8mhdcw==
Enter fullscreen mode Exit fullscreen mode

Keep in mind that openssl might not be installed on your system so it's likely that you will need to install it first in order to use it.

  • The most preferred way is to use the pseudorandom number generator - /dev/urandom since it is intended for most cryptographic purposes. We would also need to manipulate the output using tr in order to translate it. An example command is:
tr -cd '[:alnum:]' < /dev/urandom | fold -w10 | head -n 1
Enter fullscreen mode Exit fullscreen mode

With this command, we take the output from /dev/urandom and translate it with tr while using all letters and digits and print the desired number of characters.

The script

First, we begin the script with the shebang. We use it to tell the operating system which interpreter to use to parse the rest of the file.

#!/bin/bash
Enter fullscreen mode Exit fullscreen mode

We can then continue and ask the user for some input. In this case, we would like to know how many characters the password needs to be:

# Ask user for password length
clear
printf "\n"
read -p "How many characters you would like the password to have? " pass_length
printf "\n"
Enter fullscreen mode Exit fullscreen mode

Generate the passwords and then print them so the user can use them.

# This is where the magic happens!
# Generate a list of 10 strings and cut it to the desired value provided by the user

for i in {1..10}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_lenght} | head -n 1); done

# Print the strings
printf "Goodbye, ${USER}\n"
Enter fullscreen mode Exit fullscreen mode

The full script:

#!/bin/bash
#=======================================
# Password generator with login option
#=======================================

# Ask user for the string length
clear
printf "\n"
read -p "How many characters you would like the password to have? " pass_lenght
printf "\n"

# This is where the magic happens!
# Generate a list of 10 strings and cut it to the desired value provided by the user

for i in {1..10}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_lenght} | head -n 1); done

# Print the strings
printf "Goodbye, ${USER}\n"
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is pretty much how you can use a simple bash script to generate random passwords.

⚠️ As already mentioned, please make sure to use strong passwords in order to make sure your account is protected. Also, whenever is possible use 2-factor authentication as this will provide an additional layer of security for your account.

While the script is working fine, it expects that the user will provide the requested input. In order to prevent any issues, you would need to do some more advance checks on the user input in order to make sure the script will continue to work fine even if the provided input does not match our needs.

I will make sure to cover the more advance checks or the user input in my next blog posts.

Support

If you've enjoyed reading this post or learned something new and would like to support me to publish more content like this one you can support me with buying me a coffee:

Buy Me A Coffee

Thank you!

Discussion (17)

Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
alexgeorgiev17 profile image
Alex Georgiev Author • Edited

Hey,

I agree with you that saving your passwords in plain text in a file is not consider secure, hence the password will not be saved by default unless you want to do so.

The idea is for bash beginners to create a small project and have fun while doing it.

I will look into publishing a more secure updated version.

Collapse
webreflection profile image
Andrea Giammarchi

I'm afraid the internet works differently: people pick a trusted site and copy and paste (see Stack Overflow) so this is really a bad, security speaking, advice, hint, suggestion, whatsoever, beginner thingy ... because beginners should be the first one to understand that security is not a joke.

Please update this post ASAP and remove that script before it damages some clueless copy-paster.

Thanks for your help in making this site a better place for beginners too 👋

Thread Thread
alexgeorgiev17 profile image
Alex Georgiev Author

I agree with with, the script has been modified. Thanks for the valuable input!

Thread Thread
webreflection profile image
Andrea Giammarchi • Edited

I've removed my initial comment, as the post has been updated and there is no place for that comment anymore.

Thank you for the update, I know it feels less "wow" or "cool" now, but it was the right thing to do 👍

Collapse
moopet profile image
Ben Sinclair
# Check if the log file is present and if not, create it
if [[ !log_file ]]; then
  touch ~/pass_log.txt
fi
Enter fullscreen mode Exit fullscreen mode

You don't need to create a file in order to append to it - you can use >>| instead of >> later on and it will work.

Collapse
moopet profile image
Ben Sinclair • Edited

Looks like I'm mixed up.

">>|" will force it on zsh. You don't need that (and it won't be recognised) on bash. Equally, you don't need to create a file on bash prior to writing to it.

I'm mixed up because I regularly use >| to force overwriting a file when I've got noclobber set...

Collapse
alexgeorgiev17 profile image
Alex Georgiev Author

Hey,

That is indeed correct. It also saves code as well!

Collapse
alexgeorgiev17 profile image
Alex Georgiev Author

Hey,

That is correct! Thanks for sharing it.

Collapse
arifmahmudrana profile image
ARIF MAHMUD RANA

Alex why are you printing printf "$pass_output\n" where are you setting pass_output? This wasn't necessary. Also I think for script it's best to output the only intended things so that output can be piped you implementation doesn't suit that e.g I could have copied the output of script or use it for automation but this is not possible. Also why use clear printf with new line. This are all unnecessary staffs. For me short and simple

#!/bin/bash
read -p "How many characters you would like the password to have? " pass_length
tr -dc 'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~' </dev/urandom | head -c pass_length
Enter fullscreen mode Exit fullscreen mode
Collapse
alexgeorgiev17 profile image
Alex Georgiev Author

Good call, Arif! That was left over from the first version of the script which was later on changed! Thanks for pinpointing this.

Collapse
rsa profile image
Ranieri Althoff

No love for pwgen?

Collapse
alexgeorgiev17 profile image
Alex Georgiev Author • Edited

Hi,

It is great idea to use pwgen but I believe it does not come installed by default and the idea was to build the script in a way that you wont need to install any additional software.

Thanks for sharing it!

Collapse
darkain profile image
Vincent Milum Jr • Edited

If the idea is to use only things available by default, note that BASH doesn't come with every OS out there either.

POSIX sh is far more common than bash

Thread Thread
bobbyiliev profile image
Bobby Iliev

I think that if you change the shebang to /bin/sh it would also work fine.

Collapse
bobbyiliev profile image
Bobby Iliev

Great post! Thanks for sharing 🙌

If you’re a fan of open source make sure to submit a pull request to this Bash open source e-book:

github.com/bobbyiliev/introduction...

Forem Open with the Forem app