Trouble with masking password input in Python

Borut Flis picture Borut Flis · Dec 15, 2016 · Viewed 12.5k times · Source

I am using Python. I am making a script where the user has to enter the password in the terminal.

I have already found a solution on this website by using the getpass module.

new_password=getpass.getpass(prompt="Type new password: ")

The problem is I get a warning and the password input gets displayed as well.

Warning (from warnings module):
  File "C:\Python34\lib\getpass.py", line 101
    return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.

Answer

Sundara Moorthy Anandh picture Sundara Moorthy Anandh · Aug 16, 2017

Use command prompt as admin to run this program.

Reason is because system environment where stdin, stdout and stderr are connected to /dev/tty, or another PTY-compliant device.

The IDLE REPL does not meet this requirement.

And change new_password=getpass.getpass(prompt="Type new password: ") to new_password=getpass.getpass("Type new password: ") if you are using Windows OS or new_password=getpass.getpass("Type new password: ", None) for Linux distributions.

This would help you for sure:

import getpass
pw = getpass.getpass("Enter Your Password Here: ")
if pw == "password":
    print("You are Welcome...")
else:
    print("Sorry! You're are not allowed.")

As per Python documentation:

getpass.getpass([prompt[, stream]])

Prompt the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '. On Unix, the prompt is written to the file-like object stream. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows)

Changed in version 2.5: The stream parameter was added.

Note: If you call getpass from within IDLE, the input may be done in the terminal you launched IDLE from rather than the idle window itself.