A simple python script to put in the system $PATH.
Uses argparse to handle script arguments and secret to randomize the characters.
I use this to generate both usernames and password, often when setting up a bunch of test accounts.
Example to generate 5 passwords with a length of 21 characters and not using symbols.
generate-password.py -l 21 -c 5
#!/usr/bin/env python3
import argparse
import secrets
import string
def parse_arguments() -> argparse.Namespace:
"""Use argparse to get script arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--length", help="Password length", type=int, default=16)
parser.add_argument("-c", "--count", help="Number of passwords", type=int, default=1)
parser.add_argument("-s", "--symbols", help="Include symbols", action="store_true")
return parser.parse_args()
def generate_password(length: int, *, symbols: bool) -> str:
"""Generate and return random password string."""
characters = string.ascii_letters + string.digits
if symbols:
characters += string.punctuation
return "".join(secrets.choice(characters) for i in range(length))
def main() -> None:
"""System main loop."""
args = parse_arguments()
for _i in range(args.count):
password = generate_password(args.length, symbols=args.symbols)
print(password)
if __name__ == "__main__":
main()