Die Programmiersprache Ruby

Blog| Forum| Wiki  

Windows Version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
require 'Win32API'

def get_passwd( char=nil, prompt=nil, char_range=0x20..0x7F )
  getch = Win32API.new("msvcrt", "_getch", [], 'L')
  prompt ||= "Password: "
  STDERR.print prompt
  passwd = ""

  loop do
    c = getch.Call
    case c
      when 0x0d
        break
      when char_range
        passwd << c.chr
        if char
          STDERR.print char
        end
      when 0x08
        if passwd.length != 0
          STDERR.print "\x8" # BS backspace
          STDERR.print " "
          STDERR.print "\x8"
          passwd.chop!
        else
          STDERR.print "\x7" # BEL
        end
      else
        STDERR.print "\x7" # BEL if not allowed char
    end
  end
  STDERR.print "\n"

  passwd
end


passwd = get_passwd( "*" )

puts passwd
  • 16.05.2005: ergänzt um Backspace und Ausgabe auf STDERR. STDERR eignet sich besser, falls das Programm nach stdout schreibt, was z.B. bei Filtern der Fall ist. --WinfriedMueller

Einfache Linux Version

1
2
3
4
5
6
7
8
9
10
# getting Password
begin
  system "stty -echo"
  print "Passwort: "
  passwd = $stdin.gets.chomp
  print "\n"
ensure
  system "stty echo"
end
puts "Passwort: #{passwd}"


Weblinks