Skip to content

Instantly share code, notes, and snippets.

@cbsmith
Created February 25, 2018 00:39
Show Gist options
  • Save cbsmith/6a5e8241fabeb494cc676acd3ac81680 to your computer and use it in GitHub Desktop.
Save cbsmith/6a5e8241fabeb494cc676acd3ac81680 to your computer and use it in GitHub Desktop.
A pythonic/portable password generator for when you're in a pinch
"""
Generic xkcd style (https://xkcd.com/936/) password generator, because you never know when you're going to need a new password.
Usage:
mkpassword.py <num_words> <dictionary_path>
"""
from random import SystemRandom
from os.path import join, isfile
import sys
r = SystemRandom()
def get_words(additional_path=None):
paths = (join('/', 'usr', 'share', 'dict', 'words'), join('/', 'usr', 'dict', 'words'))
if additional_path:
paths += tuple(additional_path)
path = next(x for x in paths if isfile(x))
return open(path)
def get_wordset(additional_path=None):
with get_words(additional_path) as words:
return frozenset(word.strip() for word in words)
def choose_words(wordset, num_words=4):
return r.sample(wordset, num_words)
def main(args):
num_words = int(args[1]) if len(args) > 1 else 4
wordset = get_wordset(args[2] if len(args) > 2 else None)
print(' '.join(choose_words(wordset, num_words=num_words)))
if __name__ == '__main__':
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment