srinivas_rocks has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,
I am writing a simple perl script which accepts the user name and password from terminal and log's into a third party application. To hide the password while typing I used the following code:
`stty -echo` $pass=<STDIN>; `stty echo`
This works good in Linux. Is there any procedure to hide the password even in Windows ?

Thanks,
Srinivas.

Replies are listed 'Best First'.
Re: hiding password typing in Windows
by almut (Canon) on Apr 16, 2009 at 18:13 UTC

    You can use Term::ReadKey for that.

    Update: In its most simple case, this could be something like

    use Term::ReadKey; ReadMode 'noecho'; my $passw = ReadLine; ReadMode 'restore'; print "$passw\n"; # just to check

    Or, if you want to use the console/tty instead of STDIN — which would keep people from piping in passwords (like echo foo | perl 758036.pl):

    use Term::ReadKey; use Fcntl "O_RDWR"; if ($^O =~ /Win32/i) { sysopen IN, 'CONIN$', O_RDWR or die "Unable to open console for in +put: $!"; } else { open IN, "<", "/dev/tty" or die "Unable to open tty for input: $!" +; } ReadMode 'noecho', *IN; my $passw = ReadLine 0, *IN; ReadMode 'restore', *IN; print "$passw\n"; # just to check

    Or, yet another version with rudimentary editing capabilities (backspace):

    use Term::ReadKey; use Fcntl "O_RDWR"; if ($^O =~ /Win32/i) { sysopen IN, 'CONIN$', O_RDWR or die "Unable to open console for in +put: $!"; } else { open IN, "<", "/dev/tty" or die "Unable to open tty for input: $!" +; } ReadMode 'noecho', *IN; my ($ch, $passw); do { $ch = ReadKey 0, *IN; $passw .= $ch; substr($passw,-2)='' if ord($ch)==127; # BS } until ($ch eq "\n"); ReadMode 'restore', *IN; print "$passw\n";
Re: hiding password typing in Windows
by ikegami (Patriarch) on Apr 16, 2009 at 18:13 UTC
Re: hiding password typing in Windows
by mr_mischief (Monsignor) on Apr 16, 2009 at 18:18 UTC
    If you use Term::ReadKey then it should work everywhere you can find that module. Its test matrix shows the latest version works on Linux, Win32, Cygwin, Darwin (the basis of OS X, so probably there too), Solaris, and several BSD flavors (Dragonfly, OpenBSD, NetBSD, FreeBSD) under 5.10.0, which means it should be good wherever you need it.
Re: hiding password typing in Windows
by ig (Vicar) on Apr 16, 2009 at 19:23 UTC
Re: hiding password typing in Windows
by Bloodnok (Vicar) on Apr 17, 2009 at 10:37 UTC
    Why not treat yourself to a copy of the, IMO, invaluable perl cookbook ? This very subject is one of very many covered therein (Recipe 15.10).

    A user level that continues to overstate my experience :-))
      Monks, Thanks for all your responses. Term::ReadKey worked for me Below is the code that I used to get my code working
      print "\nEnter the password: "; ReadMode 2; $pass=<STDIN>; ReadMode 0;
      Hope I will get same responses for all my future queries.
      - Srinivas