Skip to content

Instantly share code, notes, and snippets.

@alanraso
Last active August 24, 2020 17:25
Show Gist options
  • Save alanraso/9b08fe0edda9fd78062e24bf03d0a7b1 to your computer and use it in GitHub Desktop.
Save alanraso/9b08fe0edda9fd78062e24bf03d0a7b1 to your computer and use it in GitHub Desktop.
Python Script to generate a random password given the length. Copies to clipboard (at least on MacOS). To generate a 20 length password: `py random-secret.py 20`.
import random
import string
import subprocess
import sys
length = int(sys.argv[1])
def write_to_clipboard(output):
process = subprocess.Popen('pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
process.communicate(output.encode('utf-8'))
def random_char():
p = random.randint(0, 100)
if p < 5:
char = ' '
elif p < 15:
char = random.choice(string.punctuation)
elif p < 65:
char = random.choice(string.ascii_letters)
else:
char = random.choice(string.digits)
return char
secret = ''
for i in range(0, length):
secret += random_char()
write_to_clipboard(secret)
print(f'Secret {secret} generated and copied to clipboard.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment