Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active November 28, 2017 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kou1okada/56c2982ec55b1d6e7fda to your computer and use it in GitHub Desktop.
Save kou1okada/56c2982ec55b1d6e7fda to your computer and use it in GitHub Desktop.
getpw.rb - Prototype of getpw function using io/console#getch function
#!/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