Python生成隨機密碼

1、生成隨機密碼要實現的功能:git

一、輸入次數,輸入多少次就產生多少條數據正則表達式

二、要求密碼必須包含大寫字母、小寫字母和數字,長度8位,不能重複app

 

2、實現代碼dom

import random,string
src = string.ascii_letters + string.digits
count = input('請確認要生成幾條密碼: ')
list_passwds = []
for i in range(int(count)):
    list_passwd_all = random.sample(src, 5) #從字母和數字中隨機取5位
    list_passwd_all.extend(random.sample(string.digits, 1))  #讓密碼中必定包含數字
    list_passwd_all.extend(random.sample(string.ascii_lowercase, 1)) #讓密碼中必定包含小寫字母
    list_passwd_all.extend(random.sample(string.ascii_uppercase, 1)) #讓密碼中必定包含大寫字母
    random.shuffle(list_passwd_all) #打亂列表順序
    str_passwd = ''.join(list_passwd_all) #將列表轉化爲字符串
    if str_passwd not in list_passwds: #判斷是否生成重複密碼
        list_passwds.append(str_passwd)
print(list_passwds)

 

3、利用集合的交運算實現spa

import random,string
passwds = []  #保存符合要求的密碼
count = input('請確認要生成幾條密碼: ')
i = 0  #記錄符合要求的密碼個數
while i < int(count):
    passwd = set(random.sample(string.ascii_letters + string.digits,8)) #從字母和數字中隨機抽取8位生成密碼
    if passwd.intersection(string.ascii_uppercase) and passwd.intersection(string.ascii_lowercase) and passwd.intersection(string.digits): #判斷密碼中是否包含大小寫字母和數字
        passwds.append(''.join(passwd))  #將集合轉化爲字符串
        i += 1 #每生成1個符合要求的密碼,i加1
print(passwds)

 

4、利用正則表達式實現code

import re, random, string

count1 = int(input('請輸入密碼個數(必須大於0): '))
i = 0
passwds = []
while i < count1:
    tmp = random.sample(string.ascii_letters + string.digits, 8)
    passwd = ''.join(tmp)
    if re.search('[0-9]', passwd) and re.search('[A-Z]', passwd) and re.search('[a-z]', passwd):
        passwds.append(passwd)
        i += 1
print(passwds)
相關文章
相關標籤/搜索