How to generate a random password using command-line tools

Here is a little command-line example to generate a random password.

To generate a random string you can use /dev/random or /dev/urandom. Both are kernel random number source devices. Read the man page to get detailed information. But if you use
cat /dev/urandom
you’ll get printable and non-printable bytes. Non-printable bytes are useless for a password. We have to use a filter to get only printable character. For this purpose we can use tr.
tr [OPTIONS] SET
In this case SET is the charset we want, e.g. only lowercase chars, only digits, etc. So we have to delete all chars execpt SET. To delete these “bad chars” we can use the options cd. c is the complement of SET and d deletes the chars in SET.
The last thing we have to set is the password length. For this purpose we’ll use the head-command with option c. This option will print only the first N bytes.

A little example:
cat /dev/urandom | tr -cd [:graph:] | head -c 10
Output:
P"xF7\VNSM

Here is a little bash-script (usage: ./pwgenerator.sh [LENGTH] [CHARSET]):

#!/bin/bash

# standard charset
CHAR="[:graph:]"
# standard password length
PWLEN=10

# is only one parameter availabe (password length)
if [ $# -eq 1 ]
then
PWLEN=$1
fi

# are two parameter available (pw length and charset)
if [ $# -eq 2 ]
then
PWLEN=$1
case $2 in
"lower")
# only lowercase characters
CHAR="[:lower:]"
;;
"upper")
# only uppercase characters
CHAR="[:upper:]"
;;
"alpha")
# lower and uppercase charaters
CHAR="[:alpha:]"
;;
"digit")
# only digits
CHAR="[:digit:]"
;;
"alnum")
# lower and uppercase characters and numbers
CHAR="[:alnum:]"
;;
"special")
# lower and uppercase chars, digits and special chars
CHAR="[:graph:]"
;;
*)
echo "invalid charset"
;;
esac
fi

password=$(cat /dev/urandom | tr -cd $CHAR | head -c $PWLEN)
echo $password

Advertisements

Posted on July 9, 2012, in Bash-Scripts and tagged , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: