Skip to content

Instantly share code, notes, and snippets.

@mlalic
Created May 26, 2014 09:37
Show Gist options
  • Save mlalic/82a4e564eb55e67dade9 to your computer and use it in GitHub Desktop.
Save mlalic/82a4e564eb55e67dade9 to your computer and use it in GitHub Desktop.
A simple random password generator CLI application. Mostly created for the purpose of testing the click package (http://click.pocoo.org/)
import click
import string
import random
def _randomize(alphabet, count):
"""Return a random string consisting of characters from the alphabet.
The length of the returned string should be ``count``.
"""
rng = random.SystemRandom()
return ''.join(rng.choice(alphabet) for _ in range(count))
def _shuffle(password_chars):
"""Shuffle the characters of the given string."""
password_chars = list(password_chars)
rng = random.SystemRandom()
rng.shuffle(password_chars)
return ''.join(password_chars)
@click.command()
@click.option('--letters', default=8,
help='Number of letters in the generated password')
@click.option('--digits', default=4,
help='Number of digits in the generated password')
@click.option('--punctuation', default=4,
help='Number of punctuation chars in the generated password')
def generate_password(letters, digits, punctuation):
"""Generates a random password containing the given number of each char
type.
"""
password_chars = ''.join([
_randomize(string.letters[0:52], letters),
_randomize(string.digits, digits),
_randomize(string.punctuation, punctuation),
])
print _shuffle(password_chars)
if __name__ == '__main__':
generate_password()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment