日常工作中经常需要用到比较复杂的密码,字母大小写+数字+特殊符号,一个两个还能自己手敲,数量大的时候,想密码都会很痛苦吧,这种内容就让代码来帮你想吧,可以让你指定密码长度.
先来编写生成随机数的代码,先创建一个Random_password.py文件,导入random模块和string模块
import random
import string
punctuation1 = '!@#$%^&*+~'
'''这里是因为我用不了那么多的特殊符号,所以我自定义了一个特殊符号变量'''
for i in range(3): # 循环几次,生成几组密码
num = random.randint(10, 30) # 指定密码长度(10位到30位)
value = ''.join(random.sample(string.digits + string.letters + punctuation1, num))
print value
这里’'punctuation1 ''这里是因为我用不了那么多的特殊符号,所以我自定义了一个特殊符号变量,在string里面有已经定义好了的特殊符号,可以直接调用,把value中的punctuation1换成string.punctuation就可以了
直接运行代码
随机密码已经出来了,现在我们将它生成界面化,这里需要导入一个Tkinter模块(python2中是’Tkinter’,python3中是’tkinter’要注意区分)
# -*- coding:UTF-8 -*-
from Tkinter import *
import random
import string
punctuation1 = '!@#$%^&*+~'
root = Tk()
def PWD():
B = int(Length.get())
for i in range(B): # 从输入框中获取生成的密码数量
num = random.randint(10, 30) # 指定密码长度
value = ''.join(random.sample(string.digits + string.letters + punctuation1, num))
print value
Label(root, text="生成密码个数:").place(relx=0, rely=0.1, relwidth=0.3, relheight=0.2)
Length = Entry(root)
Length.place(relx=0.3, rely=0.1, relwidth=0.3, relheight=0.2)
Button(root, text="生成密码", width=10, command=PWD).place(relx=0.65, rely=0.1, relwidth=0.3, relheight=0.2)
root.title('密码生成器')
root.geometry('400x200')
mainloop()
运行后会出现一个tk窗口
在输入框中输入数字,点击生成密码,会在控制台中打印出生成的密码
然后我们将生成的密码输出到文本中,便于保存
# -*- coding:UTF-8 -*-
from Tkinter import *
import random
import string
punctuation1 = '!@#$%^&*+~'
root = Tk()
def PWD():
B = int(Length.get())
for i in range(B): # 从输入框中获取生成的密码数量
num = random.randint(10, 30) # 指定密码长度
value = ''.join(random.sample(string.digits + string.letters + punctuation1, num))
r = open("password.txt", "a",) # 将随机密码输出到文档中
r.write(value + '\n')
r.close()
Label(root, text="生成密码个数:").place(relx=0, rely=0.1, relwidth=0.3, relheight=0.2)
Length = Entry(root)
Length.place(relx=0.3, rely=0.1, relwidth=0.3, relheight=0.2)
Button(root, text="生成密码", width=10, command=PWD).place(relx=0.65, rely=0.1, relwidth=0.3, relheight=0.2)
root.title('密码生成器')
root.geometry('400x200')
mainloop()
现在用py2exe模块打包成一个exe文件
首先需要写一个setpu.py脚本
from distutils.core import setup
import py2exe
setup(windows =["Random_password.py"])
进入到setpu.py文件目录中打开DOS窗口运行 python setup.py py2exe
将产生一个名为 dist 的子目录,其中包含了 helloworld.exe、python24.dll、library.zip 等等文件
点击运行这个文件,就可以在Windows系统上运行代码