Python随机生成8位密码的示例详解

2023-02-14 18:02:34 示例 生成 详解

代码示例1(8位)

import random
import string


total = string.ascii_letters + string.digits + string.punctuation


length = 8


passWord = "".join(random.sample(total, length))

print(password)

代码示例2(任意)

import random
import math


alpha = "abcdefghijklmnopqrstuvwxyz"
num = "0123456789"
special = "@#$%&*"


# 输入密码长度
pass_len = int(input("输入密码长度"))


# 设置密码长度组成格式,字母数字和特殊符号占比,以下示例50-30-20比例分配
alpha_len = pass_len//2
num_len = math.ceil(pass_len*30/100)
special_len = pass_len-(alpha_len+num_len)


password = []


def generate_pass(length, array, is_alpha=False):
       for i in range(length):
        index = random.randint(0, len(array) - 1)
        character = array[index]
        if is_alpha:
            case = random.randint(0, 1)
            if case == 1:
                character = character.upper()
        password.append(character)


# 字符
generate_pass(alpha_len, alpha, True)
# 数字
generate_pass(num_len, num)
# 特殊符号
generate_pass(special_len, special)
# 打乱顺序
random.shuffle(password)
# 转列表到字符串
gen_password = ""
for i in password:
    gen_password = gen_password + str(i)
print(gen_password)

知识补充

除了上面的两个示例代码,小编还为大家整理了一些python实现生成随机密码的方法,希望对大家有所帮助

python实现生成随机 字母 + 数字密码

#coding:utf-8
import random,string
def GetPassword(length):
  # 随机生成数字个数
  Ofnum=random.randint(1,length)
  Ofletter=length-Ofnum
  # 选中ofnum个数字
  slcNum=[random.choice(string.digits) for i in range(Ofnum)]
  # 选中ofletter个字母
  slcLetter=[random.choice(string.ascii_letters) for i in range(Ofletter)]
  # 打乱组合
  slcChar=slcLetter+slcNum
  random.shuffle(slcChar)
  # 生成随机密码
  getPwd=''.join([i for i in slcChar])
  return getPwd
if __name__=='__main__':
  print( GetPassword(6)) #GetPassword()自定义随机密码长度

Python随机生成带特殊字符的密码

#!/usr/bin/env Python
import string
from itertools import chain
from random import choice, sample
def mkpasswd(length=12, digits=4, upper=3, lower=3):
lowercase = string.lowercase
uppercase = string.uppercase
salt = '!@#$%^&*()><?'
password = list(
chain(
(choice(uppercase) for _ in range(upper)),
(choice(lowercase) for _ in range(lower)),
(choice(string.digits) for _ in range(digits)),
(choice(salt) for _ in range((length - digits - upper - lower)))
)
)
return "".join(sample(password, len(password)))
if __name__ == '__main__':
print mkpasswd()
#!/usr/bin/env python
import string
from itertools import chain
from random import choice, sample
def mkpasswd(length=12, digits=4, upper=3, lower=3):
lowercase = string.lowercase
uppercase = string.uppercase
salt = '!@#$%^&*()><?'
password = list(
chain(
(choice(uppercase) for _ in range(upper)),
(choice(lowercase) for _ in range(lower)),
(choice(string.digits) for _ in range(digits)),
(choice(salt) for _ in range((length - digits - upper - lower)))
)
)
return "".join(sample(password, len(password)))
if __name__ == '__main__':
print mkpasswd()

到此这篇关于Python随机生成8位密码的示例详解的文章就介绍到这了,更多相关Python随机生成密码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章