random

import random

DEFAULT_PASSWORD_SYMBOLS = ('23456789',  # Removed: 0,1
                            'ABCDEFGHJKLMNPQRSTUVWXYZ',   # Removed: I, O
                            'abcdefghijkmnopqrstuvwxyz')  # Removed: l

def generate_password(length=None, symbolgroups=DEFAULT_PASSWORD_SYMBOLS):
    """Generate a random password from the supplied symbol groups.

    At least one symbol from each group will be included. Unpredictable
    results if length is less than the number of symbol groups.

    Believed to be reasonably secure (with a reasonable password length!)

    """
    if length is None:
        length = 12

    r = random.SystemRandom()

    # NOTE(jerdfelt): Some password policies require at least one character
    # from each group of symbols, so start off with one random character
    # from each symbol group
    password = [r.choice(s) for s in symbolgroups]
    # If length < len(symbolgroups), the leading characters will only
    # be from the first length groups. Try our best to not be predictable
    # by shuffling and then truncating.
    r.shuffle(password)
    password = password[:length]
    length -= len(password)

    # then fill with random characters from all symbol groups
    symbols = ''.join(symbolgroups)
    password.extend([r.choice(symbols) for _i in range(length)])

    # finally shuffle to ensure first x characters aren't from a
    # predictable group
    r.shuffle(password)

    return ''.join(password)

ps= generate_password()

其中SystemRandom会产生一个平台相关的随机数生成器,
choice 方法会从给定的序列里取出一个随机element
shuffle 方法会打乱给定的list

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作者:Alon Zakai 编译:胡子大哈 翻译原文:http://huziketang.com/blog/pos...
    胡子大哈阅读 3,089评论 0 2
  • Python random包可以用来生成随机数。随机数不仅可以用于数学用途,还经常被嵌入到算法中,用以提高算法效率...
    达闻西阅读 5,695评论 1 5
  • 我们可以先来了解下伪随机数和真随机数的概念。 伪随机数:伪随机数是用确定性的算法计算出来自[0,1]均匀分布的随机...
    a479a910abe7阅读 2,507评论 0 0
  • 舍得指的舍去才会得到,只要舍去什么才能得到什么。所以,舍得,做人的大智慧,正如贾平凹先生所言:会活的人,或者说取得...
    王思瑞_732e阅读 441评论 0 0
  • 我觉得因为一段关系的结束而产生怨恨,这种怨恨如果不能消化掉,会极大的消耗掉我们的能量。爱一个人难,恨一个人更难。我...
    天边的云fly阅读 144评论 0 0