Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Last active December 23, 2015 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoleozhu/6685091 to your computer and use it in GitHub Desktop.
Save leoleozhu/6685091 to your computer and use it in GitHub Desktop.
Generate random string with python. Charset used can be specified via parameters.
#!/usr/bin/env python
import getopt
import sys
import random
import string
DEFAULT_LENGTH = 16
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "huld",
['help', 'uppercase', 'lowercase', 'digits'])
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
selection=''
for o, a in opts:
if o in ('-h', '--help'):
usage()
sys.exit()
elif o in ('-u', '--uppercase'):
selection = selection + string.uppercase
elif o in ('-l', '--lowercase'):
selection = selection + string.lowercase
elif o in ('-d', '--digits'):
selection = selection + string.digits
if not selection:
selection = string.letters + string.digits
if args:
try:
length = (int)(args[0])
except ValueError as err:
print str('length muse be an integer')
sys.exit(2)
if not length > 0:
print str('length must be a positive number')
sys.exit(1)
else:
length = DEFAULT_LENGTH
print(random_str(selection, length))
def usage():
print('''Usage: random-str [-uld] [length]
Options:
-u, --uppercase\tInclude upper case letters
-l, --lowercase\tInclude lower case letters
-d, --digits\tInclude digits
''')
def random_str(selection, length):
return ''.join(random.choice(selection) for i in xrange(length))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment