I've been working on an interactive command-line Ruby script that will prompt users for a username/password.. For the longest time I couldn't figure out how to either:
A) Turn off echo so the password wouldn't be visible as its typed.
or
B) Mask the characters with a "*"
Well in Ruby MRI - you can use the Highline gem (which is a great gem by the way) ie:
CODE:
def get_pwd(prompt='Password: ')
ask(prompt) { |q| q.echo = false }
end
get_pwd
However this won't work in JRuby because of the fact that there is no tty available in a JVM.
And that's where Java comes in...
In Java you can use the readPassword() method... So , we'll just stick that into a Ruby method.
CODE:
def read_pwd(password)
include Java
include_class 'java.lang.System'
password = System.console.readPassword.to_a
end
Voila! Now use can use the read_pwd method to get a password from a user without echoing the characters!
You need to keep in mind, however, that the variable will not contain ASCII characters , but an array with the decimal value of the characters. So you'll need to convert this back into standard ASCII characters:
CODE:
password = read_pwd(password).pack('c*')

1 comments:
test.
Post a Comment