Generate a random password

Hello All...

Can someone help me generate a random password which will be 7 characters long which contains alpha-numeric characters using shell script.

I am looking to store the output of the script that generates the password to a variable within a script and use it as the password.

Thanks,
Chiru

It's hard to generate a random but strong password. Here is a ksh script that does it: swordfish a password generator

#!/usr/bin/perl

sub randomPassword {
 my $password;
 my $_rand;

 my $password_length = $_[0];
 if (!$password_length) {
  $password_length = 10;
 }

 my @chars = split(" ",
 "a b c d e f g h i j k l m n o
  p q r s t u v w x y z A B C D
  E F G H I J K L M N O P Q R S
  T U V W X Y Z - _ % # | 0 1 2 
  3 4 5 6 7 8 9 ! ? $ @");

 srand;

 for (my $i=0; $i <= $password_length ;$i++) {
  $_rand = int(rand 71);
  $password .= $chars[$_rand];
 }
 return $password;
}

print "\n\nRandom Password = ", randomPassword(9);
print "\n\n";
1 Like

Whats wrong with:

cat /dev/urandom|tr -dc "a-zA-Z0-9-_\$\?"|fold -w 9|head

:slight_smile:

Since you asked, the problems start with your use of /dev/urandom. As one example, see "Analysis of the Linux Random Number Generator", March 6, 2006 by Gutterman, Pinkas, and Reinman.

In addition, your generator will not constrain its output to produce passwords that are easy for a human to remember.

I really encourage anyone who thinks that they have a method of generating random passwords to formally test that assumption. My script's output has passed the Diehard suite. And here is a clue, you need a random number generator that can pass Diehard. I am not aware of any version of unix or linux that comes with any random number generator that can do that. Passing Diehard is tough. No linear congruential generator, such as rand(), will even come close.

Note that even if /dev/urandom is reengineered to output random numbers, the fact that other users on the system can examine the current state of the generator and then compute previous states continues to be a problem. You really need a method that will deliver a stream of random numbers to you and only to you.

I came to the realization that Perderabo mentions many years ago.

Found a nice, small 3rd party product independant from the server that I use to create passwords. I use KeePass to generate all passwords that I don't use on a regular basis (of which are 20 characters (alpha-num-special) in length, but I do store all passwords in its database.

Has a neat copy/paste buffered (timed) facility to avoid having to retype the pasword after it's set. You and others might find it useful.

Cheers,
Cameron :wink: