Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Bash random password generator
Alex Georgiev
Alex Georgiev

Posted on • Originally published atdevdojo.com on

     

Bash random password generator

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 thedatecommand.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 | md5sum94cb1cdecfed0699e2d98acd9a7b8f6d  -
Enter fullscreen modeExit fullscreen mode

using sha256sum:

date | sha256sum30a0c6091e194c8c7785f0d7bb6e1eac9b76c0528f02213d1b6a5fbcc76ceff4  -
Enter fullscreen modeExit fullscreen mode

using base64:

date | base640YHQsSDRj9C90YMgMzAgMTk6NTE6NDggRUVUIDIwMjEK
Enter fullscreen modeExit 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 109+soM9bt8mhdcw==
Enter fullscreen modeExit 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/urandomsince it is intended for most cryptographic purposes. We would also need to manipulate the output usingtrin order to translate it. An example command is:
tr -cd '[:alnum:]' < /dev/urandom | fold -w10 | head -n 1
Enter fullscreen modeExit 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 modeExit 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 lengthclearprintf "\n"read -p "How many characters you would like the password to have? " pass_lengthprintf "\n"
Enter fullscreen modeExit 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 userfor i in {1..10}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_lenght} | head -n 1); done# Print the stringsprintf "Goodbye, ${USER}\n"
Enter fullscreen modeExit fullscreen mode

The full script:

#!/bin/bash#=======================================# Password generator with login option#=======================================# Ask user for the string lengthclearprintf "\n"read -p "How many characters you would like the password to have? " pass_lenghtprintf "\n"# This is where the magic happens!# Generate a list of 10 strings and cut it to the desired value provided by the userfor i in {1..10}; do (tr -cd '[:alnum:]' < /dev/urandom | fold -w${pass_lenght} | head -n 1); done# Print the stringsprintf "Goodbye, ${USER}\n"
Enter fullscreen modeExit 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!

Top comments(16)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
Sloan, the sloth mascot
Comment deleted
CollapseExpand
 
alexgeorgiev17 profile image
Alex Georgiev
404 bio not found
  • Location
    Sofia
  • Joined
• Edited on• 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.

CollapseExpand
 
webreflection profile image
Andrea Giammarchi
  • Joined

I'm afraid the internet works differently: people pick a trusted site and copy and paste (see Stack Overflow) so this isreally a bad, security speaking, advice, hint, suggestion, whatsoever, beginner thingy ... because beginners should be the first one to understand that security isnot 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
404 bio not found
  • Location
    Sofia
  • Joined

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

Thread Thread
 
webreflection profile image
Andrea Giammarchi
  • Joined
• Edited on• 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 👍

CollapseExpand
 
moopet profile image
Ben Sinclair
I've been a professional C, Perl, PHP and Python developer.I'm an ex-sysadmin from the late 20th century.These days I do more Javascript and CSS and whatnot, and promote UX and accessibility.
  • Location
    Scotland
  • Education
    Something something cybernetics
  • Pronouns
    They/them
  • Work
    General-purpose software person
  • Joined
# Check if the log file is present and if not, create itif[[!log_file]];thentouch ~/pass_log.txtfi
Enter fullscreen modeExit 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.

CollapseExpand
 
moopet profile image
Ben Sinclair
I've been a professional C, Perl, PHP and Python developer.I'm an ex-sysadmin from the late 20th century.These days I do more Javascript and CSS and whatnot, and promote UX and accessibility.
  • Location
    Scotland
  • Education
    Something something cybernetics
  • Pronouns
    They/them
  • Work
    General-purpose software person
  • Joined
• Edited on• Edited

Looks like I'm mixed up.

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

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

CollapseExpand
 
alexgeorgiev17 profile image
Alex Georgiev
404 bio not found
  • Location
    Sofia
  • Joined

Hey,

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

CollapseExpand
 
alexgeorgiev17 profile image
Alex Georgiev
404 bio not found
  • Location
    Sofia
  • Joined

Hey,

That is correct! Thanks for sharing it.

CollapseExpand
 
arifmahmudrana profile image
ARIF MAHMUD RANA
  • Joined

Alex why are you printingprintf "$pass_output\n" where are you settingpass_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 clearprintf with new line. This are all unnecessary staffs. For me short and simple

#!/bin/bashread-p"How many characters you would like the password to have? " pass_lengthtr-dc'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~' </dev/urandom |head-c pass_length
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
alexgeorgiev17 profile image
Alex Georgiev
404 bio not found
  • Location
    Sofia
  • Joined

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

CollapseExpand
 
rsa profile image
Ranieri Althoff
I make things run fast
  • Work
    Engineer at Volvo Cars
  • Joined

No love forpwgen?

CollapseExpand
 
alexgeorgiev17 profile image
Alex Georgiev
404 bio not found
  • Location
    Sofia
  • Joined
• Edited on• 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!

CollapseExpand
 
darkain profile image
Vincent Milum Jr
I've been coding for over 20 years now! (WOAH, do I feel old)I've touched just about every resource imaginable under the Sun (too bad they were bought out by Oracle)
  • Email
  • Location
    Seattle, WA
  • Work
    Software Engineer / DBA
  • Joined
• Edited on• 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
I am a professional DevOps Engineer with a demonstrated history of working in the internet industry. I am an avid Linux lover and supporter of the open-source movement philosophy.
  • Work
    DevEx @ Materialize | Community Manager @ DigitalOcean | Co-Founder @ DevDojo | Docker Captain
  • Joined

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

CollapseExpand
 
bobbyiliev profile image
Bobby
I am a professional DevOps Engineer with a demonstrated history of working in the internet industry. I am an avid Linux lover and supporter of the open-source movement philosophy.
  • Work
    DevEx @ Materialize | Community Manager @ DigitalOcean | Co-Founder @ DevDojo | Docker Captain
  • Joined

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...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

404 bio not found
  • Location
    Sofia
  • Joined

More fromAlex Georgiev

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp