zoukankan      html  css  js  c++  java
  • python 几种方法实现随机生成8位同时包含数字、大写字符、小写字符密码的小程序

    python 实现随机生成包8位包含大写字母、小写字母和数字的密码的程序。
    要求:
    1用户输入多少次就生成多少条密码,
    2要求密码必须同时包含大写字母、小写字母和数字,长度8位,不能重复
    代码如下:

    import string, random
    src_upp = string.ascii_uppercase
    src_let = string.ascii_lowercase
    src_num = string.digits
    lis = []
    count = input('请输入次数:').strip()
    
    
    # for 循环实现(产生密码数可能不足)
    for i in range(int(count)):
        print(i)
        # 先随机定义3种类型各自的个数(总数为8)
        upp_c = random.randint(1, 6)
        low_c = random.randint(1, 8-upp_c - 1)
        num_c = 8 - (upp_c + low_c)
        # 随机生成密码
        password = random.sample(src_upp, upp_c)+random.sample(src_let, low_c)+random.sample(src_num, num_c)
        # 打乱列表元素
        random.shuffle(password)
        # 列表转换为字符串
        new_password = ''.join(password)+'
    '
        if new_password not in lis:
            lis.append(new_password)
    with open('password.txt', 'w') as fw:
        fw.seek(0)
        fw.writelines(lis)
    fw.close()
    
    
    # while 循环实现(只有密码不重复才+1)
    j=0
    while j< int(count):
        print(j)
        upp_c = random.randint(1, 6)
        low_c = random.randint(1, 8 - upp_c - 1)
        num_c = 8 - (upp_c + low_c)
        # 随机生成密码
        password = random.sample(src_upp, upp_c) + random.sample(src_let, low_c) + random.sample(src_num, num_c)
        # 打乱列表元素
        random.shuffle(password)
        # 列表转换为字符串
        new_password = ''.join(password) + '
    '
        if new_password not in lis:
            lis.append(new_password)
            j += 1
    with open('password.txt', 'w') as fw:
        fw.seek(0)
        fw.writelines(lis)
    fw.close()
    # 用集合交集的方法生成密码:
    
    import random,string
    num = input('请输入一个数字:').strip()
    pwds = set()
    if num.isdigit():
        while len(pwds)<int(num): # 保证生成条数足够
            passwd = set(random.sample(string.ascii_letters+string.digits,8))
            set1 = set(string.ascii_uppercase).intersection(passwd)
            set2 = set(string.ascii_lowercase).intersection(passwd)
            set3 = set(string.digits).intersection(passwd)
            if set1 and set2 and set3:
                str_passwd=''.join(passwd)+'
    '#要把产生的密码变成字符串,因为前面已经给变成集合了
                pwds.add(str_passwd)
        fw =open('pwds.txt','w')
        fw.writelines(pwds)
    else:
        print('你输入的不是数字')

    运行结果如下:

    生成密码txt文件内容:

  • 相关阅读:
    oracle中文显示为问号
    oracle 11g 安装报错(agent_nmhs)
    yum源配置
    ora-00020
    mysql停止正在执行的SQL语句
    linux root用户被锁定
    MySQL8.0 根据ibd文件恢复表结构
    mysql 8.x 开启远程访问和修改root密码、
    个人博客迁移到github
    postman断言方式
  • 原文地址:https://www.cnblogs.com/wolfshining/p/7647227.html
Copyright © 2011-2022 走看看