Skip to content

Instantly share code, notes, and snippets.

@textbook
Created September 2, 2019 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save textbook/5d067ed794f8f0a41975edb9983cd9b2 to your computer and use it in GitHub Desktop.
Save textbook/5d067ed794f8f0a41975edb9983cd9b2 to your computer and use it in GitHub Desktop.
Generate moderately secure passwords
#! /usr/bin/env python3
"""Generate moderately secure passwords.
Format: {word1}{number}{word2}{symbol}
By default, words are 8-10 characters long and the number is two digits.
Suggested word source (use words_alpha.txt):
https://github.com/dwyl/english-words
"""
from argparse import ArgumentParser, FileType, RawTextHelpFormatter
from random import choice, randint, sample
from string import punctuation
from sys import argv
def generate_password(words, digits, symbols=punctuation):
"""Generate a password."""
word1, word2 = sample(words, 2)
number = randint(10 ** (digits - 1), (10 ** digits) - 1)
symbol = choice(symbols)
return f"{word1}{number}{word2}{symbol}"
def get_words(word_file, min_len=8, max_len=10):
"""Extract words from file, assuming one per line."""
return [
line
for line in map(str.strip, word_file)
if min_len <= len(line) <= max_len
]
def parse_args(args):
parser = ArgumentParser(
description=__doc__,
formatter_class=RawTextHelpFormatter,
)
parser.add_argument(
"filename",
type=FileType("r"),
help="Source word file",
)
parser.add_argument(
"--word-min",
type=int,
help="Minimum word length",
default=8,
)
parser.add_argument(
"--word-max",
type=int,
help="Maximum word length",
default=10,
)
parser.add_argument(
"--digits",
"-d",
type=int,
help="Number of digits",
default=2,
)
parser.add_argument(
"--number",
"-n",
type=int,
help="Number of passwords",
default=1,
)
return parser.parse_args(args)
if __name__ == "__main__":
args = parse_args(argv[1:])
words = get_words(
args.filename,
min_len=args.word_min,
max_len=args.word_max,
)
for _ in range(args.number):
print(generate_password(words, digits=args.digits))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment