Linux How to Generate Random Password

Linux How to Generate Random Password

Generating password is relatively simple and can be done in different ways. You can install tools to generate passwords, 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 the script:

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

generatePasswd "$1"

Leave a Comment