Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

I am running Ruby and MySQL on a Windows box.

I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things.

The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks.

How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?

like image 436
Simon Knights Avatar asked Sep 25 '08 14:09

Simon Knights


People also ask

What does ruby command do?

Ruby command is a free and open source programming language; it is flexible and is feature rich. As the name suggests, ruby indeed is a jewel language which comes at a very low entry cost. Its plug and play capability and also easily readable syntax makes it very user-friendly.

How do I open ruby console in Terminal?

Open up IRB (which stands for Interactive Ruby). If you're using macOS open up Terminal and type irb , then hit enter. If you're using Linux, open up a shell and type irb and hit enter. If you're using Windows, open Interactive Ruby from the Ruby section of your Start Menu.

How do I run a command line in ruby?

Press Ctrl twice to invoke the Run Anything popup. Type the ruby script. rb command and press Enter . If necessary, you can specify the required command-line options and script arguments.

What is Stdin ruby?

The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console. reading.rb. #!/usr/bin/ruby inp = $stdin.read puts inp. In the above code, we use the read method to read input from the console.


2 Answers

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() 
like image 51
Simon Knights Avatar answered Oct 04 '22 08:10

Simon Knights


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 :(

like image 28
jk. Avatar answered Oct 04 '22 09:10

jk.