随机生成密码作业

1、写一个生产密码的程序,输入几,就产生几条密码,密码产生的不重复。
要求密码:长度6 - 12,密码必须包含
大写字母、小写字母、数字
产生完密码后存到一个文件里面

1.首先输入生成密码的条数 需要校验输入的要是数字
2.根据输入,生成几条密码
3.生成的密码长度要是随机的,且再6-12之间
4.内容要包含大写字母、小写字母、数字
5.生产后的密码,写在文件中,每次生成密码要不重复

string中的常用的方法:
Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace

方法一
import string
import random
def create_pa():
    start=random.choice(string.digits)+random.choice(string.ascii_lowercase)+random.choice(string.ascii_uppercase)
    end=random.sample(string.digits+string.ascii_letters,random.randint(6,12)-3)
    end.append(start)
    random.shuffle(end) #洗牌
    passwerd=''.join(end)
    print(passwerd)
    return passwerd
create_pa()
def run():
    number=input('输入条数:').strip()
    password_set=set()
    if number.isdigit():
        while len(password_set) != int(number):
            result=create_pa()
            password_set.add(result+'\n')
    with open('pasw.txt','w',encoding='utf-8') as Wfile:
        Wfile.writelines(password_set)

def create_password():
    start = random.choice(string.digits) + random.choice(string.ascii_lowercase) \
    +random.choice(string.ascii_uppercase)
    end = random.sample(string.digits+string.ascii_letters,random.randint(6,12)-3)
    end.append(start)
    random.shuffle(end)
    password = ''.join(end)
    return password

  

# 方法二

import string
import random
def create_password2():
    number_set = set(string.digits)
    upper_set = set(string.ascii_uppercase)
    lower_set = set(string.ascii_lowercase)
    while True:
        before_password = random.sample(string.digits+string.ascii_uppercase+string.ascii_lowercase,random.randint(6,12)) #生成一个6-12位的字符,再大写、小写、数字的组合之间
        p = set(before_password) #存在几何种去重
        if number_set & p and upper_set & p and lower_set & p: #如果生成的字符和大写、小写、数字都有交集,则返回
            return ''.join(p)

def run():
    number = input("请输入产生的条数").strip() #1000
    password_set = set()
    if number.isdigit():
        while len(password_set)!=int(number):#0,1000
            # result = create_password()
            result = create_password2()
            password_set.add(result+'\n')

    with open('passwords.txt','w') as fw:
        fw.writelines(password_set)
run()

  

 



posted @ 2020-05-16 18:53  MLing  阅读(304)  评论(0编辑  收藏  举报