LoginSignup
2
2

More than 5 years have passed since last update.

ぱすわーどつくるよ!

Last updated at Posted at 2013-05-27
gen-pass.py
# Python3 fileencoding: utf-8

from argparse import ArgumentParser
from os import urandom
from string import printable, ascii_letters, digits


def option_parse():
    parser = ArgumentParser()
    parser.add_argument("length", type=int, nargs="?", default=12)
    parser.add_argument(
        "-c", "--charset", choices="na",
        help="a = alphabets, n = a + nums, default is printables."
    )
    return parser.parse_args()


def generate(charset, passlen):
    chars = printable[:-5]
    if charset == "a":
        chars = ascii_letters
    elif charset == "n":
        chars = digits + ascii_letters
    password = ""
    while len(password) < passlen:
        s = urandom(1)[0]
        # if Python2.x
        # s = ord(urandom(1)[0])
        if s < len(chars):
            password += chars[s]
    return password


if __name__ == "__main__":
    options = option_parse()
    charset = options.charset
    length = options.length
    print(generate(charset, length))

-h でヘルプ出るよ.-l で長さ指定して -c で使う文字の集合指定するよ.

$ python3 gen-pass.py -h
usage: gen-pass.py [-h] [-c {n,a}] [length]

positional arguments:
  length

optional arguments:
  -h, --help            show this help message and exit
  -c {n,a}, --charset {n,a}
                        a = alphabets, n = a + nums, default is printables.
$ python3 gen-pass.py
B1h(=,qW;ClW
$ python3 gen-pass.py 24 -c n
wup4sGyAb1GHp7ajE9PL5Vk0
$
2
2
0

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
2
2