Shell Safe API key / Password Generator

Published: 2020-05-19 by Pradeep Gowda.
Tagged: python, code

Recently I became aware of an instance where a program broke because the AWS secrets they were using contained special characters that are not shell safe.

Examples of such characters are:

You can be extra caution and use only the alphanumeric range, that is

But, you will also miss out on some characters that are benign.

So, I wrote this little script, which probably has 1:30::code:documentation ratio ;)

I also added a little nice UX improvement. Often times, random strings have a character or two that make it hard to double click and select the whole string. In my experience it is @ and %.

So you can choose to generate API key/passwords of any length, that are even easy double-click and copy from the shell.

The code for

#!/usr/bin/env python

Generate a shell safe API key (or password)

Generated string should not have any characters that need to be escaped in
the shell. The following characters have special meaning in some shell contexts

    ! # $ ' ( ) * , ; . < = > ? [ ] ^ { } | ~ - . : \

    -l --length length of the API key to be generated. Default is 32.
    -s --source a string of characters to use.
    -c --clickable make the string clickable.

    2020-05-19: Initial revision


import random

def apikeygen(length, source):
    return ''.join(random.sample(source, length))

if __name__ == '__main__':
    import argparse
    import string
    source = string.ascii_lowercase\
        + string.ascii_uppercase\
        + string.digits\
        + '@%_/+'
    dirty = '@%'
    parser = argparse.ArgumentParser()
        help='length of the API key to be generated.',
        help='a string of characters to use.',
        help='make the string clickable.',
    args = parser.parse_args()
    source = args.source
    if args.clickable:
        source = ''.join([c for c in source if c not in dirty])
    print(apikeygen(args.length, source))