Generate a random password from the command line

Generate a random password from the command line
# this way is NOT recommended
openssl rand -base64 32

or

LC_ALL=C tr -dc A-Za-z0-9 < /dev/urandom | head -c32; echo ''

Where 32 is the length of the generated password.

I recommend the latter because the former is a based64 encoded result of a binary array, which has a pre-defined pattern. This reduces the generated password space and produces weaker passwords than you expect in the giving size.

The latter command explanation

  • LC_ALL=C: in some locales, A-Z, a-z contain some multiple byte characters that are not supported by tr command. Thus, an error message is printed.
  • -dc flag in tr command: -d means delete characters in a given set. -c means complement.

To include special characters in the generated password, you can change the character set parameter accordingly.

LC_ALL=C tr -dc 'A-Za-z0-9 !"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~' < /dev/urandom | head -c32; echo ''

The special characters are taken from owasp:

Password special characters is a selection of punctuation characters that are present on standard US keyboard and frequently used in passwords.
The same list as string (between double quotes): " !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"

Note that the above command includes space and some characters (" &*;<=>`|) that may be forbidden in some applications.

For example, the following command, with a smaller character set, is compatible with Oracle's Identity Manager Connector Guide for Microsoft Active Directory User Management.

LC_ALL=C tr -dc 'A-Za-z0-9!#$%'\''()+,-./:?@[\]^_{}~' < /dev/urandom | head -c32; echo ''

Note: even though space is accepted but I deliberately remove it from the command because it is easy to be confused with the space around the password.

source