我的第四个项目:Python自动生成密码
点击上方蓝色字体,关注程序员zhenguo
这篇是第四个Python项目,主要使用Python内置模块,自动生成指定长度的密码。
前三个项目:
项目环境
使用
random
、string
内置模块,用于生成密码序列。click
模块之前介绍过,主要用于封装命令行接口,使用方便。Python版本是3.7.2
import random
import string
import click
功能演示
文末下载模块代码后,打开命令行窗口,执行下面一行代码:
python pwd_gen.py
默认输出密码长度为10位,顺序是完全打乱的:
$#Uyv311QC
添加参数
-shuf
,设置为False
,默认输出的密码格式为:英文字符+数字+特殊字符python pwd_gen.py -shuf=False
如下所示:
zpbiD820$@
修改密码长度为15,
python pwd_gen.py -shuf=False -len=15
生成密码,如下所示:
xcxbgok3731**#%
代码逐行解释
项目由一个模块
pwd_gen.py
组成,包括4个全局变量,一个类PwdGenerator
组成,一个cmd
命令行接口组成。4个全局变量
如下所示:
alpha_all = string.ascii_letters
alpha = alpha_all[:26]
num = string.digits
special = "@#$%&*"
alpha_all
是52个大小写字符,alpha
是26个小写字符,num
是0-9共10个数字,special
是特殊字符。类PwdGenerator
公开方法
gen_pwd
,用于生成密码;私有方法
__generate_pass
,创建指定序列、指定长度的序列。classPwdGenerator:
def__init__(self, pass_len, is_shuffle=True):
self.pass_len = pass_len
self.alpha_len = max(pass_len // 2, 1)
self.num_len = pass_len * 30 // 100
self.special_len = pass_len - (self.alpha_len + self.num_len)
self.__password = []
self.is_shuffle = is_shuffle
defgen_pwd(self):
"""
生成密码
"""
# 生成英文字符部分
self.__generate_pass(self.alpha_len, alpha, True)
# 生成数字部分
self.__generate_pass(self.num_len, num)
# 生成特殊字符部分
self.__generate_pass(self.special_len, special)
# 打乱顺序
if self.is_shuffle:
random.shuffle(self.__password)
return''.join(self.__password)
def__generate_pass(self, length, array, is_alpha=False):
for i in range(length):
index = random.randint(0, len(array) - 1)
character = array[index]
if is_alpha:
# 50%概率转化大写
case = random.randint(0, 1)
if case == 1:
character = character.upper()
self.__password.append(character)
一个cmd
命令行接口
click
模块封装命令行接口的标准用法,如下所示:@click.command()
@click.option('-len', default=10, help='密码长度')
@click.option('-shuf', default=True, help='打乱')
defcmd(len, shuf):
print(PwdGenerator(len, shuf).gen_pwd())
if __name__ == "__main__":
cmd()
项目测试
截止今晚,2022年1月11日,未发现有bug。
完整代码下载
不用打赏,点个赞或在看
就心满意足了
对应关键词
下载关键词
模块
字符
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。