Linux / UNIX: Generating Random Password With mkpasswd / makepasswd / pwgen

by on November 1, 2007 · 7 comments· LAST UPDATED November 15, 2013

in , ,

How do I generate random password to use with my shell script? How to create random password on Linux or Unix command line?

You can use the makepasswd or mkpasswd command to generate random password on Linux / UNIX like operating systems.

    Tutorial details
    DifficultyEasy (rss)
    Root privilegesYes
    RequirementsNone
    Estimated completion time10m
  1. The mkpasswd command is overfeatured front end to crypt function. makepasswd command generates true random passwords by using the /dev/random feature of Linux, with the emphasis on security over pronounceability. It can also encrypt plaintext passwords given on the command line. The updated version of generate new password, optionally apply it to a user.
  2. The makepasswd command generates true random passwords using /dev/urandom.
  3. The pwgen command generate pronounceable passwords.

Install makepasswd

Type the following command at shell prompt to instamm mkpasswd or makepasswd on Debian / Ubuntu Linux:
$ sudo apt-get install makepasswd
Sample outputs:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  nvidia-settings-experimental-310
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  libcrypt-openssl-random-perl
The following NEW packages will be installed:
  libcrypt-openssl-random-perl makepasswd
0 upgraded, 2 newly installed, 0 to remove and 15 not upgraded.
Need to get 23.1 kB of archives.
After this operation, 153 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://in.archive.ubuntu.com/ubuntu/ precise/main libcrypt-openssl-random-perl amd64 0.04-1build4 [11.2 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu/ precise/universe makepasswd all 1.10-8 [11.8 kB]
Fetched 23.1 kB in 0s (23.6 kB/s)
Selecting previously unselected package libcrypt-openssl-random-perl.
(Reading database ... 539086 files and directories currently installed.)
Unpacking libcrypt-openssl-random-perl (from .../libcrypt-openssl-random-perl_0.04-1build4_amd64.deb) ...
Selecting previously unselected package makepasswd.
Unpacking makepasswd (from .../makepasswd_1.10-8_all.deb) ...
Processing triggers for man-db ...
Setting up libcrypt-openssl-random-perl (0.04-1build4) ...
Setting up makepasswd (1.10-8) ...

mkpasswd syntax

The syntax is:

makepasswd
makepasswd [options]

Examples

Simply type the following command:
$ makepasswd
Sample outputs:

m4peQm97s

To generate passwords with exactly 16 characters long, pass the 16 option to --chars option as follows:
$ makepasswd --chars 16
Sample outputs:

cSYhQ55aNRshmBT5

To produce a total of 7 passwords instead of the default is one password, enter:
$ makepasswd --chars 16 --count 7
Sample outputs:

W6Lfrus9m08uAL7j
gdTiP2F4Td94oyWN
qoeezVzHh38m1aYK
HI0R66ExHw558L2N
5I6UH7WdUmX9e3Xg
XRTLM6V8D37JxWz0
qpvu7VaJecwG4qFb

Other command line options are as follows (see makepasswd(1)):

--crypt          Produce encrypted passwords.
--crypt-md5      Produce encrypted passwords using the MD5 digest (hash)
                       algorithm.
--cryptsalt=N    Use crypt() salt N, a positive number <= 4096.  If random
                       seeds are desired, specify a zero value (the default).
--maxchars=N     Generate passwords with at most N characters (default=10).
--minchars=N     Generate passwords with at least N characters (default=8).
--nocrypt        Do not encrypt the generated password(s) (the default).
--noverbose      Display no labels on output (the default).
--randomseed=N   Use random number seed N, between 0 and 2^32 inclusive.  A zero
                       value results in a real-random seed.  This option
                       generates predictable passwords, and should normally
                       be avoided.
--rerandom=N     Set the random seed value every N values used.  Specify zero
                       to use a single seed value (the default).  Specify
                       one to get true-random passwords, but plan on hitting
                       the CONTROL key a lot while it's running. ;)
--repeatpass=N   Use each password N times (4096 maximum, --crypt or
                       --crypt-md5 must be set and --cryptsalt may not be set).
--string=STRING  Use the characters in STRING to generate random passwords.

Note: mkpasswd and makepasswd are totally different on various distros. Please refer to your local man page for more information for exact syntax.

mkpasswd command syntax

On most distros mkpasswd is installed by default. The syntax is as follows:

mkpasswd
mkpasswd [options]
mkpasswd [options] [user]

Examples

Just type mkpasswd command and hit [enter] key:
$ mkpasswd
Sample outputs:

Password: type-Your-Password
/o88/D4SvLix2

To set length of password, enter:
$ mkpasswd -l 12
Sample outputs:

gk3Jh5s]Riaa

To store password in a shell variable, enter:
RPASS=$(mkpasswd -l 12)
echo "$RPASS"

The above shell commands will generate new password with exactly 12 characters long. You can write a script as follows:

#!/bin/bash
# ... do something
userPassword=$(mkpasswd -l 32)
# ... do with $userPassword
echo "$userPassword"
# ...

You can pass the following options to the mkpasswd command:

    -d #      (min # of digits, default = 2)
    -c #      (min # of lowercase chars, default = 2)
    -C #      (min # of uppercase chars, default = 2)
    -s #      (min # of special chars, default = 1)

The following example creates a 24-character password that contains at least 3 digits, 3 characters, and 5 uppercase characters:
$ mkpasswd -l 22 -d 3 -C 5 -s 3
Sample outputs:

h@fq'h0;w9AkTN6GovszUg

Install pwgen command

You can install and use pwgen command for automatic password generation. To install pwgen on RHEL/CentOS/Fedora Linux type yum command as follows:
# yum -y install pwgen
Sample outputs:

Loaded plugins: auto-update-debuginfo, protectbase, rhnplugin, security
This system is receiving updates from RHN Classic or RHN Satellite.
0 packages excluded due to repository protections
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package pwgen.x86_64 0:2.06-5.el6 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
=============================================================================================================================================================================
 Package                                 Arch                                     Version                                       Repository                              Size
=============================================================================================================================================================================
Installing:
 pwgen                                   x86_64                                   2.06-5.el6                                    epel                                    19 k
Transaction Summary
=============================================================================================================================================================================
Install       1 Package(s)
Total download size: 19 k
Installed size: 30 k
Is this ok [y/N]: y
Downloading Packages:
pwgen-2.06-5.el6.x86_64.rpm                                                                                                                           |  19 kB     00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : pwgen-2.06-5.el6.x86_64                                                                                                                                   1/1
  Verifying  : pwgen-2.06-5.el6.x86_64                                                                                                                                   1/1
Installed:
  pwgen.x86_64 0:2.06-5.el6
Complete!

To install pwgen on Debian/Ubuntu Linux type apt-get command as follows:
$ sudo apt-get install pwgen
Sample outputs:

[sudo] password for nixcraft:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  nvidia-settings-experimental-310
Use 'apt-get autoremove' to remove them.
The following NEW packages will be installed:
  pwgen
0 upgraded, 1 newly installed, 0 to remove and 15 not upgraded.
Need to get 21.7 kB of archives.
After this operation, 86.0 kB of additional disk space will be used.
Get:1 http://in.archive.ubuntu.com/ubuntu/ precise/main pwgen amd64 2.06-1ubuntu2 [21.7 kB]
Fetched 21.7 kB in 1s (14.8 kB/s)
Selecting previously unselected package pwgen.
(Reading database ... 539106 files and directories currently installed.)
Unpacking pwgen (from .../pwgen_2.06-1ubuntu2_amd64.deb) ...
Processing triggers for man-db ...
Setting up pwgen (2.06-1ubuntu2) ...

pwgen command syntax and examples

The syntax is:

pwgen
pwgen -N 1
pwgen [options]

Type the following command to print password by columns:
$ pwgen

Ayoh1uth chu9NahS id4iuYo0 ThaM7ic3 ohcagh7Y dooyoNg5 eeKee7ai eik4eeGi
gi7uSopa coo1aZiS eeb0Ni2k Ji1aihai faij7Ahy La7aeN4E ail1Phah IZ5shing
Shayie6o DeiB5che Ohgheic5 iChanga0 airahs5B cuoth5Xe Chagi1de weiV1ca0
Eevei6ph sieGai5o aith4Ooy Zucu1eeb iGh1ahVu pe2Jiede du0Eiviv EeW5Aiqu
Yu9Ra3la Ahg6ziaX Fei6aigu Ud1aef3u thohf1Ie Uudiosh1 ait2yahG See7eev4
zae7eiCh eiZei4ai yae8iQua Che4If3l Opho6aid aep0uS9g aev7eNof eeXai3co
xoo9Yiel zoo4Foo6 Phei1Ai4 Ohm7oqu4 Rohm3Nee neimo4Ae vai6JiuM Yohf0EiY
aizui0Xa feh1Feeg Othie8Pe eigee3Zo bei3Lice Gav7gu4i CoBoo3Ni Ae9phile
Cuj3ohqu cheip7Aa Wah9uph5 if6Ohhai Mie6vuk3 eeN9aiwi aeHaet7u Ahch8Ooc
Aix6zei5 aichah8E soo6rooC fiLoghe0 JohgooT1 eeH3lif7 oot8Urah aM0ai3ee
Thahwae1 eWiefub0 chee6Ki6 saide7Oe ozaiH1ph ahBohd8i Il7eishi Oonoo0th
mooc6aiP eeFeof4g ei0Ne8ij Xah1quei aeh9rahM aRiR4air aQu0wuP2 Muadoo8A
ye9choXe Weefuu2c aichei2H Aquoh4ir Ienahma9 vu9IYaiy roze2OoG eiHai4fo
ohmooTh2 diuZu3bu Ien5Reem eeWee7ci xo3Nahng uJ3seque seth3Xi8 ei0xi9uY
Uax0dieD aenoR3ai phie0Ait ooh3Meex Quook6oh ieru3eiH Daht4hee got3Zoov
Uph8phib ne3Lahe1 zaesah3G biiQu2ga Vo4tiogh Au1Eic3l Wais4ohl Ohy9yie2
ahLekae6 tee0haiP hah1oYie uTh7aeh9 amoh3Ier peDi5joh jaeG4xah AiZoo3ah
ub2Ayoh6 ces0Iuza Phoshij1 ooxe0Doo eoY0aev7 AepaeW1x ui8yuaNe eim3iNee
veeZeni9 Aet5enah fei2eSai Rei3faa4 peen2vaH Aeg4oiyi Eifu5vo0 Uij2thah
nuNg7ahj mequah2T Ohcai5ei ahPuos0o vu9Neong gei5Shai Aeth8ca2 Phaen3iG

To generate one password instead of a screenful passwords printed by columns:
$ pwgen -N 1
Sample outputs:

ooQue4ce 

The following example generate one password with 20 characters long:
$ pwgen 20 1
Sample outputs:

Aij2aeT2ob5yeyoonaer 

Options supported by pwgen command:

 
  -c or --capitalize
	Include at least one capital letter in the password
  -A or --no-capitalize
	Don't include capital letters in the password
  -n or --numerals
	Include at least one number in the password
  -0 or --no-numerals
	Don't include numbers in the password
  -y or --symbols
	Include at least one special symbol in the password
  -s or --secure
	Generate completely random passwords
  -B or --ambiguous
	Don't include ambiguous characters in the password
  -h or --help
	Print a help message
  -H or --sha1=path/to/file[#seed]
	Use sha1 hash of given file as a (not so) random generator
  -C
	Print the generated passwords in columns
  -1
	Don't print the generated passwords in columns
  -v or --no-vowels
	Do not use any vowels so as to avoid accidental nasty words
 
See also
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 7 comments… read them below or add one }

1 Slavko November 11, 2007 at 12:27 pm

apt-get install makepasswd

Reply

2 Gen2ly August 28, 2009 at 1:36 pm

To generate a random password for a user, you can do:

usermod -p `mkpasswd –chars=20` username

Also there char should be chars. Thanks for the tip.

Reply

3 Aimon Bustardo July 9, 2011 at 3:32 am

This is wrong (At least for RHEL and CentOS). That will generate an unencrypted password and enter it into the passwd file. Correct command is:

usermod -p `makepasswd –char=20 –crypt-md5` username

Reply

4 Dave September 17, 2009 at 3:26 pm

Another handy way of generating random passwords is this:

echo `</dev/urandom tr -dc A-Za-z0-9 | head -c8`

Obviously, this can be tweaked to your liking by adding symbols to the list of allowed characters and changing the length of the generated password in the head options. You can also use /dev/random if you want proper randomness but that does make it a whole lot slower.

Reply

5 tsolox January 11, 2011 at 9:19 pm

there is also `pwgen`

Reply

6 Bibelo May 20, 2013 at 10:02 pm

mkpasswd on Ubuntu is as the manpage says a frontend to crypt. Means it encrypts an word given as input. If you don’t type anything it will still generate something different each time for some reason (because of a salt ?).

mkpasswd is totally different on RHEL/CentOS.

Reply

7 Ramazan November 15, 2013 at 11:48 am

If openssl has been installed:

openssl rand -base64 16

Reply

Leave a Comment

Tagged as: , , , , , , , , , , ,

Previous Faq:

Next Faq: