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))
Sie können Hilfe mit -h bekommen. Geben Sie die Länge mit -l an und geben Sie den Zeichensatz an, der mit -c verwendet werden soll.
$ 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
$
Recommended Posts