26826 total geeks with 3505 solutions
Recent challengers:
  • vera level 4 - 03:10AM
  • vera level 3 - 02:59AM
  • vera level 2 - 02:12AM
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Apr 30
April Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
No longer Square:
Pear-shaped
payments biz seeks
buyer - report
Japan plans SEVEN
satellite launches
to supercharge GPS
AuDA starts final
round of DNSSEC
tests
APAC PC sales
plummet 11 per cent
after political
upheaval
[NSFW]ong> Pirate Bay"s
10 millionth
upload: Colour us
shocked, a SMUT
Researchers slurp
unencrypted Viber
messaging data with
ease
Oz Ombudsman calls
for wiretap
oversight
Boffins claim
machines now beat
humans at
face-matching
Cisco: you"re
all malware
hosts
FCC might kill off
net neutrality with
new pay-for-speed
rules ? report
Slashdot
NASA Chief Tells
the Critics of
Exploration Plan:
"Get Over It"
"Going Up" At 45
Mph: Hitachi To
Deliver World"s
Fastest Elevator
Band Releases Album
As Linux Kernel
Module
WhatsApp Is Well On
Its Way To A
Billion Users
NYPD"s Twitter
Campaign Backfires
F.C.C., In Net
Neutrality
Turnaround, Plans
To Allow Fast Lane
Mobile Game
Attempts To
Diagnose
Alzheimer"s
OpenSSL: the New
Face of Technology
Monoculture
Implant Injects DNA
Into Ear, Improves
Hearing
The Witcher 3
and Projekt Red"s
DRM-Free Stand
Article viewer

Random password generator in shell script



Written by:typedeaF
Published by:Obscurity
Published on:2004-08-03 21:19:12
Topic:Linux
Search OSI about Linux.More articles by typedeaF.
 viewed 77186 times send this article printer friendly

Digg this!
    Rate this article :
Add a little flare to a simple random password generation tool.
It's not efficent, and its not all that entropic, but its kinda cool.


#!/bin/bash
# random password generator by typedeaF
# This program has no "real" value other than introducing some bash concepts and putting them to use.
# to strip the comments: cat this.file | grep -v '^# '


# Sets the maximum size of the password the script will generate
MAXSIZE=8

# Holds valid password characters. I choose alpha-numeric + the shift-number keyboard keys
# I put escape chars on all the non alpha-numeric characters just for precaution
array1=(
q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D
F G H J K L Z X C V B N M 1 2 3 4 5 6 7 8 9 0 ! @ # $ % ^ & * ( )
)

# Used in conjunction with modulus to keep random numbers in range of the array size
MODNUM=${#array1[*]}

# Keeps track of the number characters in the password we have generated
pwd_len=0

# Bash's command substitution syntax to store the results of the tput command
term_clear=$(tput clear)

# Stores the number of lines or rows on the terminal display
max_lines=$(tput lines)

# Stores the number of columns on the terminal display
max_cols=$(tput cols)

# Finds the appropriate spot to indent for horizontally centered output
indent=$(( ((max_cols / 2)) - ((MAXSIZE / 2)) ))

# Finds the vertical center of the terminal.
line_num=$(( max_lines / 2 ))

# Clear the screen
echo $term_clear

# The outer while loop starts at 0 and loops till MAXSIZE, creating a passwd char each iteration.
# The shells $RANDOM variable creates a semi-random unsigned number. This is our entropy. =x
# x simply holds some random unsigned int that will be used to make the character scramble.
# 500 was choosen for speed and nothing else. Leave out the mod 500 if you want or change it.
# The inner loop displays the password characters. Tput keeps the cursor in the proper position.
# Mod MODNUM keeps the random number inside the size of the array so it doesnt over index.
while [ $pwd_len -lt $MAXSIZE ]
do
  x=$(($RANDOM%500))
  y=0
  while [ $y -lt $x ]
  do
    ((y++))
    index=$(($RANDOM%$MODNUM))
    tput cup $line_num $(( indent + pwd_len ))
    echo -n "${array1[$index]}"
  done
  ((pwd_len++))
done

# Place the cursor at the bottom of the screen --where is usually at.
tput cup $max_lines 0

exit 0

Did you like this article? There are hundreds more.

Comments:
twr_sparks
2004-08-04 01:07:09
kick ass :)
vigour
2005-02-21 14:53:17
head -c 10 | /dev/random | uuencode -m - | tail -n 2 | head -n 1

that example provides random passwords too...

and to make it simple i use the following example:

#!/usr/bin/perl

if($ARGV[0] !~ /^\d+/) { $count=9; }
else { $count=$ARGV[0]; }
system("head -c $count /dev/random | uuencode -m - | tail -n 2 | head -n 1 ");


the only parameter is the lenght of the password we want to get...
typedeaF
2005-06-04 16:51:16
Nice alternate examples vigour. I was actually emphasizing bash, as in a bash tutorial. Since there is no section for shell scripts, I placed it under "Linux". Nice examples of how to pipe commands together tho.
Anonymous
2006-08-30 01:06:37
Great job.Excellent script.

Sanjiv
Anonymous
2006-11-24 10:05:35
Really impressive !
Great !
Anonymous
2006-12-04 12:44:18
AWESOME SCRIPT I WILL SO MAKE SURE TO... SCRIPT IT! YAAAAAAY SCRIPT! WOOOOH, YEAH! AWESOME! WOOOOOOO HOOOOOOOOOOO SCRIPT!

Its so awesome, I just had party in the comment box, and by the time you read this, it will be over. BLOCK THIS IP ADDRESS. ;\
skrye
2006-12-08 18:42:48
Yeah, good stuff
Anonymous
2007-03-21 16:25:27
I think the alternate is suppposed to be:
head -c 10 < /dev/random | uuencode -m - | tail -n 2 |d -n 1
Anonymous
2007-07-03 07:48:47
Great Efforts Never Fail
Anonymous
2007-07-21 20:44:55
I modified the code a bit. Like this more. I use it for creating secure WPA2 passphrases.
But hey, thanks for getting me started!

#!/bin/bash
MAXSIZE=62
array1=(
q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D
F G H J K L Z X C V B N M 1 2 3 4 5 6 7 8 9 0 \! \@ \# \$ \% \^ \& \* \( \)
\! \@ \# \$ \% \^ \& \* \( \) \! \@ \# \$ \% \^ \& \* \( \) \! \@ \# \$ \%
)
MODNUM=${#array1[*]}
pwd_len=0
while [ $pwd_len -lt $MAXSIZE ]
do
    index=$(($RANDOM%$MODNUM))
    echo -n "${array1[$index]}"
    ((pwd_len++))
done
echo
exit 0
Anonymous
2007-10-24 16:17:17
Cool scriped we needed something simple here to generate passwords for users that was easy to pull out problem charicters (such as l and 0 and o) Which have a tendancy to cause problems with users

Worked like a charm

Oh and I added a parameter pass to the script as well as some of the different servers have different password length requirements

So bassically
MAXSIZE=$1 was the line I changed

Very handy thanks
Anonymous
2007-12-19 22:38:00
simpler version
#!/bin/bash


# Sets the maximum size of the password the script will generate
MAXSIZE=8

# Holds valid password characters. I choose alpha-numeric + the shift-number keyboard keys
# I put escape chars on all the non alpha-numeric characters just for precaution
array1=(
w e r t y u p a s d f h j k z x c v b m Q W E R T Y U P A D
F H J K L Z X C V B N M 2 3 4 7 8 ! @ $ % \# \& \* \= \- \+ \?
)

# Used in conjunction with modulus to keep random numbers in range of the array size
MODNUM=${#array1[*]}

# Keeps track of the number characters in the password we have generated
pwd_len=0

while [ $pwd_len -lt $MAXSIZE ]
do
  index=$(($RANDOM%$MODNUM))
  password="${password}${array1[$index]}"
  ((pwd_len++))
done
echo $password
Anonymous
2008-02-14 07:09:41
Sehr gut gemacht ein Lob an dich auch aus Deutschland (Germany)
MfG C.Schumacher
Anonymous
2008-02-15 01:05:41
Awesome - now to strip out meta characters so can use this for temp files in Solaris 10:

head -2 /dev/random | uuencode -m - | tail -3 | head -1 | sed 's/[^A-z0-9]/Y/g'

Gregg
Anonymous
2008-03-25 20:45:27
On my linux box, I use this to make random passwords:
uuidgen | cut -c-8
Anonymous
2008-04-03 23:57:52
That's a bit OTT.
function randompass {
        pass=</dev/urandom tr -dc A-Za-z0-9| (head -c $1 > /dev/null 2>&1 || head -c 8)
        echo $pass
}
Anonymous
2008-07-03 23:14:22
Hello averyone,

Can someone please help me with this...

I would need to set up a passwd wiht the following steps:

- At least 2 uppercase letters
- At least 2 numbers letters
- The passwd should not start or finish wiht numbers.

Examples: LL67jsds, HH89cskj,kjUU89jj, Jkj8Jo9J, etc
Anonymous
2008-07-06 13:32:03
Hey all, I use this little beauty. Its based on the /dev/random entropy pool, so is much more random than most others, and filters out untypable ascii characters. Its not exactly shell scripting, but since the release of OpenJDK...

/*
The purpose of this app is to generate a cryptographically
strong WPA password based on the Linux Entropy Pool at /dev/random.
This will not run on windows, nor would I wish it to. The Linux Entropy Pool is more random
then CryptGenRandom anyway =P

This code is released into the Public Domain,
http://creativecommons.org/licenses/publicdomain/
*/
import java.io.*;
public class SecPass {
private static final int pwlen = 63; //The desired length of the password. 63 is the default maximum.
private static final int bufbase = 1; //trying to conserve the entropy pool.
private static String buf = "";
public static void main(String[] args){
        BufferedReader random = null;
        try {
            random = new BufferedReader(new FileReader("/dev/random")); //trying to eke a little more performance out of it
            char[] tmp = new char[bufbase];
            do {
                random.read(tmp);
                if (tmp[bufbase - 1] <= 126 && tmp[bufbase - 1] >= 33) {
                    buf = buf.concat(String.valueOf(tmp[bufbase - 1]));
                }
            } while (buf.length() < pwlen);
            System.out.println(buf);
        } catch (IOException ex) {
                System.out.println("IO Error");
        } finally {
            try {
                random.close();
                System.exit(0);
            } catch (IOException ex) {
                System.out.println("Stream close error");
                System.exit(-1);
            }
        }
}}


If your entropy pool is too small, it may take a sec to run, but enjoy!

-Matthias A
Anonymous
2008-09-15 17:58:20
uuidgen would only include hexadecimal characters(lower case for a-f) thus making it a "little" easier to crack if the person cracking was able to know this before trying to crack a hash.
Anonymous
2009-08-06 12:13:49
Quote:

Hello averyone,

Can someone please help me with this...

I would need to set up a passwd wiht the following steps:

- At least 2 uppercase letters
- At least 2 numbers letters
- The passwd should not start or finish wiht numbers.

Examples: LL67jsds, HH89cskj,kjUU89jj, Jkj8Jo9J, etc



tr -dc '[:print:]' < /dev/urandom | fold -w 8 |grep .*[0-9].*[0-9].* -|grep ^[^0-9] |grep .*[A-Z].*[A-Z].* -|head
Anonymous
2009-08-06 17:27:55
ooppss

missed the the last bit:

Quote:

or finish wiht numbers


tr -dc '[:print:]' < /dev/urandom | fold -w 8 |grep .*[0-9].*[0-9].* -|grep ^[^0-9] |grep [^0-9]$ |grep .*[A-Z].*[A-Z].* -|head


Anonymous
2009-08-12 22:17:56
Hi. I made this script but I need random generator in awk and he must be the same like this for those arguments 2, 1 and 0:
#!/bin/bash
while [ 1 ]
do
echo "What is the number of arguments"
echo "Arguments:"
read arguments

case $arguments in
  "2")
  echo "What is the number of passwords:"
  echo -n "Number: "
  read number
  echo "How long must be the password:"
#this mean how many must be the letters etc. in password
  echo -n "long: "
read long
echo "//Generated password:"
  pass=< /dev/urandom tr -cd '[:graph:]' | fold -w $long | head -n $number
  echo $pass; break ;;
  "1")
  echo "What is the number of passwords:"
  echo -n "Number: "
  read number
  
echo "//Generated password:"
  
  pass=< /dev/urandom tr -cd '[:graph:]' | fold -w 8 | head -n $number
  echo $pass ; break ;;
  "0")
echo "//Generated password:"
   pass=< /dev/urandom tr -cd '[:graph:]' | fold -w 8 | head -n 1
   echo $pass ; break ;;
  *)continue ;;
esac
done
Anonymous
2009-11-08 17:07:12
Quote Anon:
can u tell me in details about what is cookie?
A cookie is how a site recognizes your browser from other browsers; it's how when you check the remember me checkbox, you don't have to login again. Articulos Gratis
Anonymous
2011-03-18 08:27:22
hi ,

please could anyone help me in generating random commands for telnet

thanks
vani
2011-03-18 08:32:37
hi ,

please could anyone help me in generating random commands for telnet

thanks
vani
2011-03-18 08:32:43
hi ,

please could anyone help me in generating random commands for telnet

thanks
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
bb
start svn on system boot in debian on Tue 21st Jul 10am
http://linux.justinhartman.com/Startup_S cript_for_Subversion I found this a really simple explanation of how to start svn when the server boots
bb
SSHFS: Super Easy File Access over SSH on Wed 18th Feb 1pm
This was really useful, and worked great to communicate between servers. http://www.linuxjournal.com/article/8904 Thanks to gabbs
bb
hellanzb nzb news downloader for NSLU2 on Tue 22nd May 7pm
Someone introduced me to the joyful NZB file recently. Its truly a wonderful invention, and allows my to explore usenet binary grabbing using my NSLU2. as previous nntp readers id tried made the process too painful. So simply .... 1) apt-get inst
bb
edna mp3 streaming for nslu2 on Wed 9th May 11am
I've been streaming music from my home NSLU2 server for a while now using mt-daapd (firefly) which is an ITunes server for linux. I can connect to my home network from work using ITunes and a little daap proxy app called rendevous. My friend was doing
Adnurak
How to choose the right Linux Distro on Thu 9th Nov 7pm
This is mainly for new users who want to try out Linux for the first time, but try it out if you're experienced in Linux anyway, it's kinda fun. What with all these different distributions of Linux that you hear about all the time, it's hard to choose
ketan404
my blog on Thu 9th Nov 6am
http://ketan404.blogspot.com
bb
Tweaking Apache and Mysql for Low Memory on Fri 20th Oct 11am
i implemented this to tweak my apache/mysql for better performance on my NSLU2. Hard to tell if its helping much though ;-) Mysql really doesnt run too well with apache on NSLU2 so I dont use it for much. http://www.unixshell.com/wiki/index.php/ Optimiz
Adnurak
Fate - A Linux Security Simulation Written in C++ on Fri 20th Oct 6am
Fate is a simulation of a Linux system written in C++ and meant for DOS (runs fine in winxp and winme by just doubleclicking) that according to the creator, m101, shows you the basics of security in different Linux systems, including but not limited to, M
bb
Article on building rtorrent for arm5vtel NSLU2 with debianslug on Thu 19th Oct 7am
I wrote an article today on my efforts at compiling rtorrent for debianslug. its here ... Article on building rtorrent/libtorrent for arm5vtel NSLU2 with littleendian debianslug
bb
How to mount .iso file on NSLU2 running debianslug on Tue 19th Sep 12pm
If like me your running debianslug on an NSLU2 and you'd like to mount an iso file so it can be directly streamed to Xbox Media Centre (its a beautiful solution isnt it!) then simply do the following. Ensure you have loop support in your debianslug k

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
Linux Test Simple by a13x4nd7u

This is a simple Linux commands test.
Linux Quiz by abhijangda

Trivia about your favorite OS
Linux Administration by typedeaF

Testing your knowledge of Linux administration tools, very light shell scripting, and good high level understanding of how the OS works at the user level. Anyone who has worked with Linux for 1-3 years should do good.
Linux Commands (Part 1) by nirus

If you think you know the linux command-line then this test is for you. For reference purposes, it is based on Debian/GNU Linux with a BASH Shell.


     
Your Ad Here
 
Copyright Open Source Institute, 2006