The following code is a simple random password generator that spits out a randomized password based on some input flags.
import string
import random
import argparse
def gen_char(lower, upper, digit, special):
_lower_letters = string.ascii_lowercase
_upper_letters = string.ascii_uppercase
_digits = string.digits
_special = "!@#$%^&*()"
_rand = random.SystemRandom()
_case = ""
if lower:
_case += _lower_letters
if upper:
_case += _upper_letters
if digit:
_case += _digits
if special:
_case += _special
if _case:
return _rand.choice(_case)
else:
return _rand.choice(_lower_letters+_upper_letters+_digits+_special)
def main():
"""
The following lines of code setup the command line flags that the
program can accept.
"""
parser = argparse.ArgumentParser()
parser.add_argument("length", type=int, help="length of password")
parser.add_argument("--lower", "-l",
help="Generates passwords with lower case letters",
action="store_true")
parser.add_argument("--upper", "-u",
help="Generates passwords with upper case letters",
action="store_true")
parser.add_argument("--digit", "-d",
help="Generates passwords with digits",
action="store_true")
parser.add_argument("--special", "-s",
help="Generates passwords with special characters",
action="store_true")
args = parser.parse_args()
"""
The following lines of code calls upon the gen_char() function to
generate the password.
"""
_pass = ""
for x in range(args.length):
_pass += gen_char(args.lower, args.upper, args.digit, args.special)
print _pass
main()
The code is in working condition. I'm looking for tips in terms of coding styles, readability and perhaps optimizations if any.
If anyone is interested, the code can be found on github.
_case
is a particularly good name here. Consideralphabet
instead. \$\endgroup\$