Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Oct 29th, 2006, 4:20 PM   #1
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 639
Rep Power: 4 Jessehk is on a distinguished road
Nothing Special, just a password generator

I needed some random passwords so I made a quick utility in Python using the optparse module.

It might be useful to others, so I figured what the hell, I'd post it here.

password.py (this file is in a directory I've appended to the environmental variable PYTHONPATH)
python Syntax (Toggle Plain Text)
  1. #!/usr/bin/env python
  2.  
  3. """
  4. Facilities for generating random
  5. passwords using the random module provided
  6. in the python standard library.
  7. """
  8.  
  9. import string
  10. import random
  11.  
  12. options = {
  13. "upper" : string.uppercase,
  14. "digit" : string.digits,
  15. "punct" : string.punctuation,
  16. "lower" : string.lowercase
  17. }
  18.  
  19. class Generator(object):
  20. def __init__(self, length, *args):
  21. self.possible = parse_options(*args)
  22. self._length = length
  23.  
  24. def generate(self):
  25. """Generate the password randomly
  26. from the possibilites specified in
  27. __init__().
  28.  
  29. The resulting password is
  30. returned. A new password is created every time
  31. this method is called.
  32. """
  33. return ''.join(random.choice(self.possible) for l in xrange(self._length))
  34.  
  35. def __len__(self):
  36. return self._length
  37.  
  38. def parse_options(*args):
  39. possible = []
  40.  
  41. for key in args:
  42. if options.has_key(key):
  43. possible.extend(options[key])
  44.  
  45. return possible
  46.  
  47. def main():
  48. print Generator(10, "upper", "punct", "digits", "lower").generate()
  49.  
  50. if __name__ == "__main__":
  51. main()

pgen (placed in a directory in my PATH)
python Syntax (Toggle Plain Text)
  1. #!/usr/bin/env python
  2.  
  3. import optparse
  4. import sys
  5.  
  6. import password
  7.  
  8. defined_options = password.options.keys()
  9.  
  10. def configure_options(usage):
  11. """
  12. Define the options for this program.
  13. """
  14. parser = optparse.OptionParser(usage=usage)
  15.  
  16. parser.add_option("-d", "--digits",
  17. help="Include the digits [0-9].",
  18. action="store_true", default=False, dest="digit")
  19.  
  20. parser.add_option("-p", "--punct",
  21. help="Include common punctuation characters.",
  22. action="store_true", default=False, dest="punct")
  23.  
  24. parser.add_option("-u", "--uppercase",
  25. help="Include uppercase characters.",
  26. action="store_true", default=False, dest="upper")
  27.  
  28. parser.add_option("-c", "--downcase",
  29. help="Include lowercase characters.",
  30. action="store_true", default=False, dest="lower")
  31.  
  32. parser.add_option("-l", "--length",
  33. help="The number of characters in the password.",
  34. type="int", dest="length")
  35.  
  36. return parser
  37.  
  38. def parse_opts(options):
  39. """
  40. Return a list of
  41. the options specified by the
  42. user.
  43.  
  44. Takes the options after they have been
  45. parsed by the OptionParser.
  46.  
  47. Example output: ["lower", "upper", "punct"]
  48. """
  49. result = []
  50.  
  51. for k in defined_options:
  52. # if this option has been included by
  53. # the user...
  54. if getattr(options, k):
  55. # ...append it to the output list.
  56. result.append(k)
  57.  
  58. return result
  59.  
  60. def error_check(options, parser):
  61. """
  62. Check for any invalid or missing options.
  63. """
  64. if not options.length:
  65. parser.error("A value for length is required.")
  66. else:
  67. # We need at least 1 type of
  68. # character in the password
  69. if not True in [getattr(options, k) for k in defined_options]:
  70. parser.error("Please specify at least one type of character.")
  71.  
  72. def main():
  73. parser = configure_options("usage: %prog [options]")
  74. (options, args) = parser.parse_args(sys.argv)
  75. error_check(options, parser)
  76.  
  77. print password.Generator(options.length, *parse_opts(options)).generate()
  78.  
  79. if __name__ == "__main__":
  80. main()

Example usage:
$ pgen
usage: pgen [options]

pgen: error: A value for length is required.
$ pgen --help
usage: pgen [options]

options:
  -h, --help            show this help message and exit
  -d, --digits          Include the digits [0-9].
  -p, --punct           Include common punctuation characters.
  -u, --uppercase       Include uppercase characters.
  -c, --downcase        Include lowercase characters.
  -l LENGTH, --length=LENGTH
                        The number of characters in the password.
$ pgen -l10 -d
5722058132
$ pgen -l10 -dc
4d2ybboqth
$ pgen -l10 -dcu
L37uL2QN1W
$ pgen -l10 -dcup
S?U71dU8PT
$ pgen -l64 -dcup
I[Lqg#gcI5YdM;s%C(sF+{yl#EVsF%e/&20P^dCK&z!Lu,s,Y"^B0V!?W5,,VjRG
$ pgen --length=abc
usage: pgen [options]

pgen: error: option --length: invalid integer value: 'abc'
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
simple password checker RemoteC2 C++ 13 Aug 10th, 2006 5:07 PM
[Python] Password Generator bulio Show Off Your Open Source Projects 2 Feb 28th, 2006 3:01 AM
password box ragenuub Visual Basic 5 Nov 15th, 2005 3:46 PM
Password Generators 2roll4life7 Show Off Your Open Source Projects 0 Oct 23rd, 2005 9:32 PM
Just a small password generator Jessehk Show Off Your Open Source Projects 3 Sep 16th, 2005 8:41 AM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 3:42 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC