dmathieu - Ruby console ask for a password

Ruby console ask for a password

Wednesday, 16 December 2009 in Development Articles by Damien Mathieu Creative Commons License

When you get user information in console, you might, sometimes, need to get sensible information. Password for example. Which can’t be displayed on the screen for security reasons. The library Ruby Password allows you to do that quite easily. However it implies you depend on this library. And that’s something I don’t wish. Particularly for something so simple.

The solution I’m suggesting here uses the linux features (not tested on windows. But who’s still using it today ? :trollface: ).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
begin
  print 'Username:'
  username = $stdin.gets.chomp

  print 'Password:'
  # We hide the entered characters before to ask for the password
  system 'stty -echo'
  password = $stdin.gets.chomp
  system 'stty echo'
rescue NoMethodError, Interrupt
  # When the process is exited, we display the characters again
  # And we exit
  system 'stty echo'
  exit
end

What are we doing ? We start by asking the user’s nickname.

1
2
print 'Username:'
username = $stdin.gets.chomp

This is not a sensible data and can be displayed. Nothing specific to do. Then we ask for a password. Here we must hide it.

1
2
3
4
print 'Password:'
system 'stty -echo'
password = $stdin.gets.chomp
system 'stty echo'

The “stty -echo” will hide every character that should be displayed on the console. The “stty echo” displays them again.

Until there it works. Cool ! But somehowe we have a boring user, whom decides at the last moment to enter Ctrl-C to quit the program and finds himself in console with the -echo mode and doesn’t see what he enters in. We’ve just lost a friend.</p>

Fortunately we have exceptions notifications and we already detect an Interrupt to exit the program cleanly. Then we just have to display the characters again when there’s this interrupt :)

1
2
3
4
5
6
begin
  # ...
rescue NoMethodError, Interrupt
  system 'stty echo'
  exit
end

Hop ! :) And the project that uses this is glynn