zl程序教程

您现在的位置是:首页 >  Python

当前栏目

生成你的自定义密码本Python

2023-04-18 15:16:02 时间

python生成一个自定义密码本

import itertools as its
import os

# 定义生成密码本的函数

def generate_passwords(length, combination):
    if combination == "1":
        words = "1234567890"
    elif combination == "2":
        words = "abcdefghijklmnopqrstuvwxyz"
    elif combination == "3":
        words = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    elif combination == "4":
        words = "!@#$%^&*()_+"
    else:
        words = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+"

    r = its.product(words, repeat=length)
    file_name = f"{length}_{combination}.txt"
    if os.path.isfile(file_name):
        print(f"{file_name} already exists. Please choose a different length or combination.")
    else:
        with open(file_name, "a") as f:
            for i in r:
                f.write("".join(i) + "
")
        print(f"{file_name} generated successfully!")


# 主函数,获取用户输入并生成密码本

def main():
    length = input("输入生成密码的长度: ")
    while not length.isdigit():
        length = input("Invalid input. 重新输入: ")

    combination = input("Please choose the combination of the password:
1. 数字
2. 小写字母
3. 大写字母
4. 特殊字符
5. 所有组合
")
    while not set(combination).issubset(set("12345")) or not combination:
        combination = input("Invalid input. 重新输入: ")
    
    generate_passwords(int(length), combination)

if __name__ == "__main__":
    main()

运行结果如下:

请输入您要生成的密码长度: 10
请选择密码组合方式:
1.纯数字 2.字母小写 3.字母大写 4.特殊字符 5.所有组合
请输入对应数字:1234
生成的密码为:  C4D.)({+/# 

用户可以通过输入不同的数字来选择密码组合方式,也可以通过输入数字串来选择多种组合方式的结合。

生成一个随机密码和一个当前组合方式的密码本