Generate a random password from the command line

Generate a random password from the command line
LC_ALL=C tr -dc A-Za-z0-9 < /dev/urandom | head -c32; echo ''
All alphanumeric characters


LC_ALL=C tr -dc A-HJ-NP-Za-fhjkmnpr-z2-8 < /dev/urandom | head -c32; echo ''
[Recommended] Omit confusing characters: IOlo01qg9


openssl rand -base64 32
Based-64 encoded string from random bytes stream

Where 32 is the length of the generated password.

I recommend the 2 formers because the results of the last command is a based64 encoded result of a binary array, which has a pre-defined pattern. This reduces the generated password randomness and produces weaker passwords than expected in the given size.

The 2 former commands 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.
  • In the second command, we omit all characters which look similar: I, O, l, o, 0, 1, q, g, 9.

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.


Buy Me A Coffee