Hiding Keyboard Input From the Screen

For my current job I'm in charge of writing a script that requires a person to input their password and me being the semi-security conscious individual that I am knew that regular input for a script like this would be bad, as that would allow for over the shoulder (literally) view of someone's password. This is just unacceptable.

To solve this problem I hit the internets for a way to hide user input in Perl script. And in my travels I came across this old PERL FAQ site. I decided to try out the code and update it, throw it into a little dummy script. This is what I got (minus the dummy script):

  1. sub get_password
  2. {
  3. print "enter your password: ";
  4. system("stty -echo");
  5. chop(my $password=<>);
  6. print "\n";
  7. system("stty echo");
  9. return $password;
  10. }

Saved it, ran it, and Holy Missing Characters Batman, it worked. So just as a mental exercise, I wanted to see if I could get it to emulate the password request when you run sudo, and I wrote this up in Python (because I need the practice):

  1. #!/usr/bin/python
  3. import os
  4. import getpass
  6. def get_password():
  7. #print "Please enter your password:"
  8. os.system("stty -echo")
  9. password = raw_input( getpass.getuser() + "'s password")
  10. os.system("stty echo")
  11. print "\n"
  13. return password
  15. def main():
  16. local_password = get_password()
  17. print local_password
  19. main()

And again... it worked. Of course I finally realized that the reason why it worked is because of the line "stty -echo". Taking that I typed it into a standard terminal and after hitting enter the results were the same. My terminal functioned normally, but without showing me the characters I was typing. After returning my terminal back to normal I decided to read a little more about stty. After digging through the man page for a little while I came across this argument which is an alias for echo:

echo erase characters as backspace-space-backspace

Thus the reason why I couldn't see anything change is because my terminal is treating all characters I type on the screen as a three part sequence of non alphanumeric characters. Although I find this a little odd; I have to just go with the words of Bugs Bunny on this one, “I don't ask questions. I just have fun.”

If you made it this far down into the article, hopefully you liked it enough to share it with your friends. Thanks if you do, I appreciate it.

Bookmark and Share

Syndicate content