How can Perl ask for a password without showing it in the terminal?

How can I request a password from a terminal user without entering a password in the terminal? There is a similar question for How can I enter a password using Perl and replace the characters with "*"? but the answers seem outdated or broken.

I searched for answers to this question and was not satisfied with the questions on the later pages of the results, which answered tangentially to other problems.

In addition, perlfaq8 has an example that is incomplete (oh, and who used to do this;).

use Term::ReadKey; ReadMode('noecho'); my $password = ReadLine(0); 

When you do this without resetting the terminal, nothing more! Unfortunately,

I am also looking for new answers or modules that we can provide to those who want to do this.

+7
terminal passwords perl
source share
2 answers

To use Term :: ReadKey , this works:

 sub prompt_for_password { require Term::ReadKey; # Tell the terminal not to show the typed chars Term::ReadKey::ReadMode('noecho'); print "Type in your secret password: "; my $password = Term::ReadKey::ReadLine(0); # Rest the terminal to what it was previously doing Term::ReadKey::ReadMode('restore'); # The one you typed didn't echo! print "\n"; # get rid of that pesky line ending (and works on Windows) $password =~ s/\R\z//; # say "Password was <$password>"; # check what you are doing :) return $password; } 
+7
source share

You can also use IO :: Prompter :

$ perl -MIO::Prompter -wE '$pass = prompt("Password: ", -echo => "*"); $pass =~ s/\R\z//; say $pass'

It is probably too difficult to ask for a password, but it is useful if you need to call other input types as well. Note that you need Term :: ReadKey for password masking to work. Unfortunately, the module does not warn about this during assembly. You will find out that you are in this situation if a single-line generator generates a warning:

Warning: the next input will be in plain text

The prompt() routine is called with the -echo flag, but the Term::ReadKey not available to implement this function. The login will be carried out as usual, but this warning is issued so that the user does not enter something secret, expecting that he will remain hidden, but it will not.

How this warning message matches the value given in the explanation is outside of me, but, oh, good.

Note that on Windows, the module leaves CR at the end of the input line, which chomp does not delete (because it searches for the CRLF sequence). This is why I use \R in the above example. See RT # 118255 .

+1
source share

All Articles