16
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python でテキトーにパスワード生成

Last updated at Posted at 2016-02-23

string モジュールには色んなカテゴリの文字の集合が定義されてる。

console
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
'\t\n\x0b\x0c\r '
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

これを使ってテキトーにパスワード生成してみる。

console
>>> import random, string
# 4文字な数字の場合
>>> ''.join([random.choice(string.digits) for i in range(4)])
'7602'
>>> ''.join([random.choice(string.digits) for i in range(4)])
'7531'

# 8文字な英数字の場合
>>> ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
'84xemCAc'
>>> ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
'cjiGNd2k'

# 12文字な英数記号の場合
>>> ''.join([random.choice(string.punctuation + string.ascii_letters + string.digits) for i in range(12)])
'9f58EN+}rbW8'
>>> ''.join([random.choice(string.punctuation + string.ascii_letters + string.digits) for i in range(12)])
'DP4E,N}jtT;W'

必要に応じて長さや文字の種類が変えれるから、パスワード以外にも使える。かも?
毎回対話シェル叩くのはめんどくさいので、 argparse モジュールとか使ってシェルから叩けるようにしとくと良いかと。

16
23
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?