michltm michltm - 7 months ago 27
Python Question

generate unique passwords with python

I use a simple python script to generate thousands of random passwords of length 16.

But is there a way to check that the password is unique i.e. it hasent been already generated before printing it?

Here is the actual script:

import os, random, string

length = 16
chars = string.ascii_letters + string.digits + '!?@#%&'
random.seed = (os.urandom(1024))

result=[];

for num in range(0,100):

result.append(''.join(random.choice(chars) for i in range(length)));

for i in result:
print i

Answer

If you change result to a set and use its add method you will ensure no duplicates by design.

result = set() # {} literal syntax works in 2.x
while len(result) < 1000:
  result.add(''.join(random.choice(chars) for i in range(length))) 
Comments