一、需求
编写测试脚本,生成批量的随机密码
二、实现
(1)生成指定长度的随机英文/数字/符号
#获取随机长度的字符串
import random
import string
def GetRandomString(pwd_sample,pwd_length_min,pwd_length_max):
letters1 = string.ascii_letters
letters2 = string.digits
letters3 = string.punctuation
ranLen = random.randint(pwd_length_min, pwd_length_max)
str = ""
if pwd_sample==1:
for i in (1,11):
str = str + letters1
elif pwd_sample==2:
for i in (1, 11):
str = str + letters2
elif pwd_sample==3:
for i in (1, 11):
str = str + letters3
else:
return ('输入错误')
#通过join()方法连接字符
GetStr = ''.join(random.sample(str,ranLen))
#输出的字符串是纯数字,保存在csv时会变成科学计数法
#加【\t】进行转义,保存为数字格式
if pwd_sample==2:
GetStr = GetStr+"\t"
return GetStr
if __name__ == '__main__':
pwd_sample = int(input('请输选择密码格式:1、英文 2、数字 3、符号'))
pwd_length_min = int(input('请输入密码长度最小值'))
pwd_length_max = int(input('请输入密码长度最大值(<20)'))
str1 = GetRandomString(pwd_sample,pwd_length_min,pwd_length_max)
print(str1)
(2)生成指定长度的随机英文+数字+符号
import random
import string
def GetRandomString(pwd_sample,pwd_length_min,pwd_length_max):
letters1 = string.ascii_letters
letters2 = string.digits
letters3 = string.punctuation
ranLen = random.randint(pwd_length_min, pwd_length_max)
str = ""
if pwd_sample==1:
for i in (1,11):
str = str + letters1
elif pwd_sample==2:
for i in (1, 11):
str = str + letters2
elif pwd_sample==3:
for i in (1, 11):
str = str + letters3
elif pwd_sample==4:
for i in (1, 11):
str = str + letters1 + letters2 + letters3
else:
return ('输入错误')
#通过join()方法连接字符
GetStr = ''.join(random.sample(str,ranLen))
return GetStr
if __name__ == '__main__':
pwd_sample = int(input('请输选择密码格式:1、英文 2、数字 3、符号 4、英文+数字+符号 '))
pwd_length_min = int(input('请输入密码长度最小值:'))
pwd_length_max = int(input('请输入密码长度最大值:'))
str1 = GetRandomString(pwd_sample,pwd_length_min,pwd_length_max)
print(str1)
(3)将数据保存在csv文件
if __name__ == '__main__':
pwd_sample = int(input('请输选择密码格式:1、英文 2、数字 3、符号 4、英文+数字+符号 '))
pwd_length_min = int(input('请输入密码长度最小值:'))
pwd_length_max = int(input('请输入密码长度最大值:'))
pwd_num = int(input('请输入需要构造的密码个数:'))
file = open('passWord.csv','w',newline='')
writer = csv.writer(file)
for i in range(1,pwd_num):
str1 = GetRandomString(pwd_sample,pwd_length_min,pwd_length_max)
writer.writerow([str1])
print(str1)
file.close()