How to generate random password using Bash shell scripting
In Category Bash
All Linux systems have a special device “/dev/urandom” which can throw random bytes while reading. But this device gives binary data which may contain non-printable characters. However as we need human-readable characters for a password, we can pick all alpha-numeric characters out the random binary data read from the special device.
The following script reads a binary stream from /dev/urandom and picks up first 8 alpha-numeric characters and form a 8-chracter long random password. If you want to change the length of the password, change “-c8” option given to “head” to anything you want. For example “-c16” will give you 16-character long random password.
[neo@techpulp ~]# cat randpass.sh
#!/bin/bash
function randpass
{
echo `</dev/urandom tr -dc A-Za-z0-9 | head -c8`
}
randpass
[neo@techpulp ~]#
You can see the script generating different (random) password each when it is run.
[neo@techpulp ~]# sh randpass.sh aS4S6A0d [neo@techpulp ~]# sh randpass.sh c9JqEMZP [neo@techpulp ~]# sh randpass.sh XktXtdhy [neo@techpulp ~]#
was it really necessary to create a function??
why not just
[]
#!/bin/bash
echo </dev/random tr -dc A-Za-z0-9 | head -c8
[\]
there i just turned 6 lines into 2
Is possible to add some special chars to improve the password strength (just enclose it between apostrophes ‘ ‘ ):
echo `</dev/urandom tr -dc A-Za-z1-9′\!”.$%&/()=?|@#[]{}-_.:,;’ | head -c12`
I also wanted symbols for my password.
Using [:graph:] as the set for tr only allows printable characters (not including spaces):
echo `</dev/urandom tr -dc [:graph:] | head -c 10`