Last active
November 28, 2017 10:38
-
-
Save kou1okada/56c2982ec55b1d6e7fda to your computer and use it in GitHub Desktop.
getpw.rb - Prototype of getpw function using io/console#getch function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# | |
# getpw.rb | |
# Copyright (c) 2016 Koichi OKADA. All right reserved. | |
# This script distributed under the MIT license. | |
# | |
require 'io/console' | |
def getpw | |
pw = c = "" | |
begin | |
c = STDIN.getch | |
case c | |
when /[\x03]/ # C-c | |
Process.kill('SIGINT', Process.pid) | |
when /[\x1a]/ # C-z | |
Process.kill('SIGSTOP', Process.pid) | |
when /[\b\x7f]/ # C-h|BS | |
if 0 < pw.length | |
STDERR.print "\b \b" | |
pw.chop! | |
end | |
when /[\x15]/ # C-u | |
STDERR.print "\b \b" * pw.length | |
pw = "" | |
when /[[:print:]]/ | |
STDERR.print "*" | |
pw += c | |
else | |
STDERR.print "*" | |
pw += c | |
end | |
end until c =~ /[\r\n]/ | |
pw | |
end | |
if __FILE__ == $0 | |
STDERR.print "Password: " | |
password = getpw.chomp! | |
STDERR.puts | |
print password | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment