linux how to generate random password

Answer

Generating password is relative simple and can be done different ways. You can install tools to generate password, a few examples:

  • mkpasswd (Debian/Ubuntu)
  • makepasswd (Debian/Ubuntu)
  • pwgen (CentOS/Fedora/RHEL)

When you don't have installed these tools, here are useful commands:

date +%s | sha256sum | base64 | head -c 32 ; echo

We used time in seconds as a input to hash function sha-256 and print first 32 chars. You can replate sha256sum with other hash function (md5sum).

strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 32 | tr -d '\n'; echo

/dev/urandom is the built-in feature which generate random chars.

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c32; echo

Another way using /dev/urandom, even simpler.

You can also create script:

generatePasswd () {
local l=$1
[ "$l" == "" ] && l=16
tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
generatePasswd "$1"

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.

 

More Information

BASH scripting course

We prepared for you video course Marian's BASH Video Training: Mastering Unix Shell, if you would like to get much more information.

Thank you. Marian Knezek