Skip to content

Instantly share code, notes, and snippets.

@fabianofranz
Created May 11, 2012 04:24
Show Gist options
  • Save fabianofranz/2657516 to your computer and use it in GitHub Desktop.
Save fabianofranz/2657516 to your computer and use it in GitHub Desktop.
get password - Ruby - any platform - no gems needed
# --- Platform inspectors
def jruby? ; RUBY_PLATFORM =~ /java/i end
def windows? ; RUBY_PLATFORM =~ /win(32|dows|ce)|djgpp|(ms|cyg|bcc)win|mingw32/i end
def unix? ; !jruby? && !windows? end
# --- Lé code
def ask_for_password_on_unix(prompt = "Enter password: ")
raise 'Could not ask for password because there is no interactive terminal (tty)' unless $stdin.tty?
$stdout.print prompt unless prompt.nil?
$stdout.flush
raise 'Could not disable echo to ask for password securely' unless system 'stty -echo'
password = $stdin.gets
password.chomp! if password
password
ensure
raise 'Could not re-enable echo while asking for password' unless system 'stty echo'
end
def ask_for_password_on_windows(prompt = "Enter password: ")
raise 'Could not ask for password because there is no interactive terminal (tty)' unless $stdin.tty?
require 'Win32API'
char = nil
password = ''
$stdout.print prompt unless prompt.nil?
$stdout.flush
while char = Win32API.new("crtdll", "_getch", [ ], "L").Call do
break if char == 10 || char == 13 # return or newline
if char == 127 || char == 8 # backspace and delete
password.slice!(-1, 1)
else
password << char.chr
end
end
puts
password
end
def ask_for_password_on_jruby(prompt = "Enter password: ")
raise 'Could not ask for password because there is no interactive terminal (tty)' unless $stdin.tty?
require 'java'
include_class 'java.lang.System'
include_class 'java.io.Console'
$stdout.print prompt unless prompt.nil?
$stdout.flush
java.lang.String.new(System.console().readPassword(prompt));
end
def ask_for_password(prompt = "Enter password: ")
%w|windows unix jruby|.each do |platform|
eval "return ask_for_password_on_#{platform}(prompt) if #{platform}?"
end
raise "Could not read password on unknown Ruby platform: #{RUBY_DESCRIPTION}"
end
@skull-squadron
Copy link

Fixed the jruby code and generally cleaned it up a bit: https://gist.github.com/2040373

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment