美文网首页
生成包含大小写符号数字随机密码 (Python)

生成包含大小写符号数字随机密码 (Python)

作者: slords | 来源:发表于2021-03-18 09:44 被阅读0次
    # python
    import random
    
    
    # 取字范围 可自定义调整
    POOL_NUMBER = tuple(chr(i) for i in range(ord('0'), ord('9') + 1))
    POOL_LOW_CHAR = tuple(chr(i) for i in range(ord('a'), ord('z') + 1))
    POOL_UP_CHAR = tuple(chr(i) for i in range(ord('A'), ord('Z') + 1))
    POOL_SYMBOL_CHAR = ('!', '%', '&', '-', '.', '@', '[', '/', ']', '_', '^', '`', '~')
    
    POOL_LIST = [POOL_NUMBER, POOL_LOW_CHAR, POOL_UP_CHAR, POOL_SYMBOL_CHAR]
    
    
    def gen_passwd(length: int = 16) -> str:
        max_count = sum([len(_) for _ in POOL_LIST])
        assert len(POOL_LIST) <= length <= max_count, ValueError(length, max_count)
        pool_list = [list(_) for _ in POOL_LIST]
    
        char_list = []
        for list_ in pool_list:
            random.shuffle(list_)
            char_list.append(list_.pop(0))
    
        all_char = sum(pool_list, [])
        random.shuffle(all_char)
        char_list += all_char[:length - len(POOL_LIST)]
        random.shuffle(char_list)
        return ''.join(char_list)
    
    
    if __name__ == '__main__':
        print(gen_passwd())
    

    相关文章

      网友评论

          本文标题:生成包含大小写符号数字随机密码 (Python)

          本文链接:https://www.haomeiwen.com/subject/gzkucltx.html