Skip to content

Instantly share code, notes, and snippets.

@lukecampbell
Created November 9, 2021 23:15
Show Gist options
  • Save lukecampbell/7eb51f73d968d40636081a27387f02c2 to your computer and use it in GitHub Desktop.
Save lukecampbell/7eb51f73d968d40636081a27387f02c2 to your computer and use it in GitHub Desktop.
genpass.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
'''
from __future__ import print_function
from argparse import ArgumentParser
import sys
import random
CAT_CHAR = '[]{}!@#$%^&*()_+-=,./<>?:";\'\\|'
def main(args):
'''
Generate a password
'''
if args.secure:
password = gen_secure_pass(passlen=args.length, use_specials=(not args.alnum))
print(password)
return 0
words = get_words(args.words_file)
buf = []
word_count = args.word_count or 2
for i in range(word_count):
word = random.choice(words)
if random.randint(0, 1):
word = word.capitalize()
buf.append(word)
buf.append(random.choice(CAT_CHAR))
if i % 3 == 0:
buf.append(str(random.randint(0, 100)))
print(''.join(buf))
return 0
def get_words(words_file=None):
words_file = words_file or '/usr/share/dict/words'
with open(words_file) as f:
words = f.read().splitlines()
return words
def gen_secure_pass(passlen=32, use_specials=True):
alnum = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
specials = '~!@#$%^&*()_+`-=[]{};\':",./<>?\\|'
allowed_set = alnum
if use_specials:
allowed_set += specials
buf = ''.join((random.choice(allowed_set) for i in range(passlen)))
return buf
if __name__ == '__main__':
parser = ArgumentParser(description=main.__doc__)
parser.add_argument('-w', '--words-file', help='words file to use')
parser.add_argument('-c', '--word-count', help='number of words to use')
parser.add_argument('-n', '--length', type=int, default=32, help='Password length for secure passwords')
parser.add_argument('-s', '--secure', action='store_true', help='Generate password containing random alphanumeric and special characters')
parser.add_argument('-a', '--alnum', action='store_true', help='Use alphanumerics only')
args = parser.parse_args()
sys.exit(main(args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment