This recipe generates a pseudo-random password of a prescribed length. It also lets you specify what characters are not permitted in the password or specify what characters are.
1 2 | from random import *
passwordGen = lambda length, badChars = '',alpha = '1234567890qwertyuiop[]asdfghjkl;zxcvbnm,.!@#$%^&*()_+-=-{}:<>|QWERTYUIOPASDFGHJKLZXCVBNM~`?': "".join([list(set(alpha)^set(badChars))[randint(0,len(list(set(alpha)^set(badChars)))-1)] for i in range(length)])
|
Example telling the computer what characters not to include:
>>> passwordGen(13,'!@#$%_+-=:;')
'^j1XXrRc0C{~O'
Example telling the computer what characters to use:
>>> passwordGen(15,'','abc')
'aabaccbaaccacab'
This is the short form of the code. It is a bit slower because it calculates list(set(alpha)^set(badChars)) twice. The longer, but a tiny bit faster way is:
from random import *
def passwordGen(length,badChars = '',alpha = '1234567890qwertyuiop[]asdfghjkl;zxcvbnm,.!@#$%^&*()_+-=-{}:<>|QWERTYUIOPASDFGHJKLZXCVBNM~`?'):
alphaNew = list(set(alpha)^set(badChars))
return "".join([alphaNew[randint(0,len(list(alphaNew)-1)] for i in range(length)])