Generate password in python

前端 未结 9 1968
既然无缘
既然无缘 2020-12-12 21:51

I\'dl like to generate some alphanumeric passwords in python. Some possible ways are:

import string
from random import sample, choice
chars = string.letters          


        
9条回答
  •  时光取名叫无心
    2020-12-12 22:27

    I suggest the following for those stuck on python <3.6:

    import os, math, string, struct
    
    def generate_password(pass_len):
        symbols = string.printable.strip()
        return ''.join([symbols[x * len(symbols) / 256] for x in struct.unpack('%dB' % (pass_len,), os.urandom(pass_len))])
    

    This has the advantage over Ben Mosher's solution that the each symbol from symbols has an equal change of occurring whereas using modulus slightly favors the first symbols in the alpabet. The alphabet of symbols is also larger in this suggestion.

提交回复
热议问题