Below I’ll describe a couple of nice methods to generate passwords using Python and Bash.

Actually there are a lot of ways you can accomplish this especially with bash, but using the /dev/urandom file seems to be the most clever one.

The /dev/urandom device doesn’t only generate read-friendly characters, so it’s best to filter out the ones we’d like. The best tool for that would be tr.

$ cat /dev/urandom | tr -dc [:alnum:] | head -c 10

This will generate a password from 10 alphanumeric characters.

It will not include some characters though, such as . ! – _ which are useful for passwords. So this line would be a little more “secure”.

$ cat /dev/urandom | tr -cd “[:alnum:]\.\-_\!” | head -c 10

To generate a password in Python, using the string and random module would be a clever touch. Let’s try something like this,

>>> import string, random
 >>> def passgen(length) :
 ... keys = list(string.ascii_letters + string.digits)
 ... return "".join(random.choice(keys) for i in range(length)

With this definition of the passgen function, we can generate alphanumeric passwords with whatever length we want. If you’d like to include all characters available, try the one below:

>>> import string, random
 >>> def passgen(length) :
 ... keys = list(string.ascii_letters + string.digits + ".,;:-_()@\"\\[]?!'^+*$%&/=~`<>|")
 ... return "".join(random.choice(keys) for i in range(length)

A sample output :

>>> passgen(16)
 'pP!3p"(-uxdIqpAK'

You can find some methods of password generation using MD5 algorithms. For example for password generation in MySQL some people prefer this method;

>SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 5)

But this will generate very very weak passwords, no uppercase characters and a lot of characters missing, not even to mention the non-alpha numeric characters. Also you’ll have a limit for maximum character number since the MD5 algorithm has a limit for it. So it’s best to stay away from the md5 approach for password generation. Some people also use it for bash password generation too (which is wrong! due to same reasons)

Leave a Reply

Your email address will not be published. Required fields are marked *