Created
April 1, 2016 16:43
-
-
Save mitchsmith/e6f54c8b75ca090f0fc09410066b8dbd to your computer and use it in GitHub Desktop.
Python getopt example: genpass - A pasword/secret_key generator for all occasions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""USAGE: | |
genpass [OPTIONS] | |
OPTIONS: | |
-h, --help | |
Display this help message. | |
-a, --allow=dec|hex|alpha|alnum|all | |
Allowable characters; default=all | |
-s, --size=<size> | |
Character length of the output; default=8 | |
""" | |
import sys | |
import getopt | |
import random | |
digit = map(chr, range(48,58)) | |
lowercase = map(chr, range(97, 123)) | |
uppercase = map(chr, range(65, 91)) | |
symbols = list("!$%^&*-_+=,.?~") | |
def usage(): | |
print(__doc__) | |
def create_pw(size, allow): | |
allowed = ''.join({ | |
'dec': digit, | |
'hex': digit + map(chr, range(65, 71)), | |
'alpha': uppercase + lowercase, | |
'alnum': uppercase + lowercase + digit, | |
'all': uppercase + lowercase + digit + symbols | |
}[allow]) | |
return ''.join(random.choice(allowed) for i in range(size)) | |
def main(argv): | |
size = 8 | |
allow = "all" | |
try: | |
opts, args = getopt.getopt(argv, "ha:s:", ["help", "allow=", "size="]) | |
except getopt.GetoptError: | |
usage() | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt in ("-h", "--help"): | |
usage() | |
sys.exit() | |
elif opt in ("-s", "--size"): | |
size = int(arg) | |
_debug = 1 | |
elif opt in ("-a", "--allow"): | |
allow = arg | |
extra = " ".join(args) | |
print(create_pw(size, allow)) | |
if extra: | |
print("** Extra ignored. Use > or >> to redirect stdout**") | |
if __name__ == '__main__': | |
main(sys.argv[1:]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment