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

# 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))