随机密码生成

2022-11-23
1
import sys
2
import string
3
import secrets
4
5
alphabet = string.ascii_letters + string.digits
6
punctuation = string.punctuation
7
8
def random_passwd(length=18):
9
"""随机生成指定位数的密码"""
10
11
passwd_table = alphabet + punctuation
12
13
while True:
14
passwd = ''.join(secrets.choice(passwd_table) for i in range(length))
15
if (any(p.islower() for p in passwd) and \
16
any(p.isupper() for p in passwd) and \
17
any(p in passwd for p in punctuation) and \
18
sum(p.isdigit() for p in passwd) >= 3):
19
20
return passwd
21
22
if __name__ == '__main__':
23
length = int(sys.argv[1])
24
passwd = random_passwd(length)
25
print(f'\n{length}位随机密码: {passwd}')