Skip to content

Instantly share code, notes, and snippets.

@patrikalienus
Last active April 8, 2024 12:23
Show Gist options
  • Save patrikalienus/12dd70d91571ff0d3ba26bb2bee1fed5 to your computer and use it in GitHub Desktop.
Save patrikalienus/12dd70d91571ff0d3ba26bb2bee1fed5 to your computer and use it in GitHub Desktop.
Random password generator
#!/usr/bin/python3
# Learning python project.
# I bet there are better ways of doing things than this, but it works well, especially paired with a workflow in Alfred.
# -c, --chars Number of characters to use
# -r, --range Amount of passwords to generate
import sys
import getopt
import string
import secrets
# Settings
minchars = 12
default_no_of_chars = 15
# Setup
chars = default_no_of_chars
argv = sys.argv[1:]
specials = "!#$%&()*+-?=@[]^_|"
alphabet = string.ascii_letters + string.digits + specials
# Create a password with the given characters
def create_password(chars) -> str:
chars = int(chars)
if chars < minchars:
print("Minimum character for passwords is set to " + str(minchars))
chars = minchars
while True:
password = "".join(secrets.choice(alphabet) for i in range(chars))
if (
any(c.islower() for c in password)
and any(c.isupper() for c in password)
and sum(c.isdigit() for c in password) >= 3
):
break
return password
passwords = []
def get_opts() -> list:
try:
opts, args = getopt.getopt(argv, "c:r:", ["chars=", "range="])
return opts
except:
print("Error in getopt.getopt()")
# Show password
def show_password() -> None:
pwdrange = 1
global passwords
passed_options = get_opts()
if passed_options:
for opt, arg in passed_options:
if opt in ["-r", "--range"]:
pwdrange = arg
for opt, arg in passed_options:
if opt in ["-c", "--chars"]:
chars = arg
# No options passed, must set chars.
else:
chars = default_no_of_chars
# Create password(s)
for i in range(int(pwdrange)):
password = create_password(chars)
passwords.append(password)
for i in passwords:
print(i)
# Execute
show_password()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment