Generate Random Passwords

You can use this ruby code to generate random passwords. Or, save it as an executable file for the Mac OS X command line.

Do you need to make as many passwords as I do? Do you have a mac, and are you comfortable with the command line? You can save this code in an executable file and run it as a command. It makes a random password and copies it to the clipboard


#!/usr/bin/env ruby
 
# read and writes to the mac clipboard
class MacClipboard
   class << self
     def read
       IO.popen('pbpaste') {|clipboard| clipboard.read}
     end
     def write(stuff)
       IO.popen('pbcopy', 'w+') {|clipboard| clipboard.write(stuff)}
     end
   end
end #class MacClipboard
 
# creates a random password
# include unwanted characters in the - %w
def random_password(size = 12)
  chars = (('a'..'z').to_a + 
          ('0'..'9').to_a + 
          ('A'..'Z').to_a + 
          ("!".."/").to_a) - %w(i o 0 1 l 0)
    (1..size).collect{|a| chars[rand(chars.size)] }.join
end
 
newpass = random_password
MacClipboard.write(newpass)
puts newpass

Thanks to Peter Cooper and Evan Light for the snippets of code, I just tied them together and added symbols and uppercase characters.

You can also find this code on GitHub

Category:

Author: ivanoats

Created on: August 9th, 2009

Comments

Ivan Storck

11 months ago

I had to change this slightly for ruby 1.9 because String is no longer an enumerable. I had to add in the call to String.chars , which is an enumerable.


  score += 1 if pass.chars.any? {|char| char =~ /[a-z]/ }
  score += 1 if pass.chars.any? {|char| char =~ /[A-Z]/ }
  score += 1 if pass.chars.any? {|char| char =~ /[0-9]/ }
  score += 1 if pass.chars.any? {|char| char =~ /[!$()+,-.\/]/}

leave a comment

Back to article list