DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   ruby (http://www.daniweb.com/code/ruby.html)
-   -   Quick password generator (http://www.daniweb.com/code/snippet507.html)

Jessehk ruby syntax
Jun 15th, 2006
This is a simple, but complete (pseudo) random password generator.

Examples of usage:

$ ruby pgen.rb
soovmuvytv
$ ruby pgen.rb --length=20
bynnugipyeeghdbihcdn
$ ruby pgen.rb --length=20 -n
v3ji3awj1trzjlda5oax
$ ruby pgen.rb --length=20 -np
:sa6vafpummpttjp?qo:

For complete usage guidelines, run
$ ruby pgen.rb --help

This (hopefully) serves as both a useful program, and a simple example of the use of the optparse module.

EDIT:Code fixed to correct error. Everything should be working now.

  1. # pgen.rb
  2. # by Jesse H-K on Thursday, June 15 2006
  3.  
  4. require 'optparse'
  5.  
  6. class Array
  7. def random_choice
  8. self[rand(self.length)]
  9. end
  10. end
  11.  
  12. def parse_options(args)
  13. options = {}
  14.  
  15. options[:length] = 10
  16.  
  17. opts = OptionParser.new do |opts|
  18. opts.banner = "Usage: pgen.rb [options]"
  19.  
  20. opts.on("-n",
  21. "--numbers",
  22. "Include the digits [0-9] in the password.") do |n|
  23. options[:numb] = n
  24. end
  25.  
  26. opts.on("-p",
  27. "--punctuation",
  28. "Include common punctuation characters in the password.") do |p|
  29. options[:punct] = p
  30. end
  31.  
  32. opts.on("-u",
  33. "--uppercase",
  34. "Include uppercase letters in the password.") do |u|
  35. options[:upcase] = u
  36. end
  37.  
  38. opts.on("-l",
  39. "--length=[LENGTH]",
  40. Integer,
  41. "The length of the password. Default is 10 characters.") do |l|
  42. options[:length] = l
  43. end
  44. end
  45.  
  46. opts.parse!
  47. options
  48. end
  49.  
  50. class PasswordGenerator
  51. @@options = { :numb => ('0'..'9').to_a,
  52. :punct => %w(. , ! ? @ & :),
  53. :upcase => ('A'..'Z').to_a }
  54.  
  55. def initialize(length, *opts)
  56. @possible = *('a'..'z')
  57. @length = length
  58.  
  59. parse_content_options(opts)
  60. end
  61.  
  62. def parse_content_options(opts)
  63. opts.each { |opt| @possible.concat(@@options[opt]) if @@options.key? opt }
  64. end
  65.  
  66. def generate
  67. (1..@length).inject("") { |passwd, e| passwd << @possible.random_choice }
  68. end
  69.  
  70. private :parse_content_options
  71. end
  72.  
  73. options = parse_options(ARGV)
  74.  
  75. puts PasswordGenerator.new(options[:length], *options.keys).generate