使用python生成随机密码

使用python生成随机密码,密码长度13位,一般密码文件不能以?和! 开头的,需要将这两个开头的密码文件排除掉。

有两种方式。

第一种方式

import random
import string

# 定义密码长度
password_length = 13

# 定义密码字符集合
password_characters = string.ascii_letters + string.digits + string.punctuation

# 生成10个随机密码并写入文件
for i in range(10):
    # 生成随机密码
    password = ''.join(random.choice(password_characters) for i in range(password_length))

    # 确保密码不以'!'或'?'开头
    while password.startswith(('!', '?')):
        password = ''.join(random.choice(password_characters) for i in range(password_length))

    # 将密码写入文件
    filename = f"password_{i+1}.txt"
    with open(filename, 'w') as f:
        f.write(password)

 

第二种使用faker模块。

from faker import Faker
import random

fake = Faker()

# 生成10个随机密码
passwords = []
while len(passwords) < 10:
    password = fake.password(length=13)
    if not password.startswith(('!', '?')):
        passwords.append(password)

# 将密码写入文件
for i, password in enumerate(passwords):
    filename = f"password_{i+1}.txt"
    with open(filename, 'w') as f:
        f.write(password)

 

posted @ 2023-07-01 12:36  ken-yu  阅读(506)  评论(0编辑  收藏  举报