python生成隨機密碼串
python 的random模塊可以生成隨機數,主要用這個生成隨機密碼。
string模塊中的3個函數:string.letters,string.printable,string.printable
>>> import string >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.digits '0123456789' >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
以下是隨機生成10組包含數字、大小寫字母的隨機數生成方法,大家可以指定隨機數的長度:
#!/usr/bin/env python #-*- coding:utf-8 -*- ''' 簡短地生成隨機密碼,包括大小寫字母、數字,可以指定密碼長度 #生成隨機密碼 ''' import random import string #python3中爲string.ascii_letters,而python2下則可以使用string.letters和string.ascii_letters def GenPassword(length): chars=string.ascii_letters+string.digits return ''.join([random.choice(chars) for i in range(length)]) ''' #得出的結果中字符會有重複的 #return ''.join(random.sample(chars, 15))#得出的結果中字符不會有重複的 ''' if __name__=="__main__": '''#生成10個隨機密碼 ''' for i in range(10): #密碼的長度爲15 print GenPassword(15)
python passwd.py BdMXufZF5KtYhjJ EdQIJyMjoB7OR2t pbKk58ptWQIwf9Z puFyPnwBmX9mSyW 9Rna9D8oxEbJS7s dh2fEFKHQouXj9F WZRNrc0k94Yn8Ks MsheWb2leZXEAVI rBqF7C6VjprLN6Z 99a3ZyW37cB7BeJ