How can I read a password from the command line in Ruby?

According to the Highline doc, this seems to work. Not sure if it will work on Windows.

#!/usr/local/bin/ruby
require 'rubygems'
require 'highline/import'

username = ask("Enter your username:  ") { |q| q.echo = true }
password = ask("Enter your password:  ") { |q| q.echo = "*" }

Here's the output on the console:

$ ruby highline.rb 
Enter your username:  doug
Enter your password:  ******

Poor man's solution:

system "stty -echo"
# read password
system "stty echo"

Or using http://raa.ruby-lang.org/project/ruby-password/

The target audience for this library is system administrators who need to write Ruby programs that prompt for, generate, verify and encrypt passwords.

Edit: Whoops I failed to notice that you need this for Windows :(


To answer my own question, and for the benefit of anyone else who would like to know, there is a Ruby gem called HighLine that you need.

require 'rubygems'
require 'highline/import'

def get_password(prompt="Enter Password")
   ask(prompt) {|q| q.echo = false}
end

thePassword = get_password()

Tags:

Ruby