I'm writing a console program with Python for Windows.
The user needs to login to use the program. When they enter their password, I'd like each character to be echoed as "*" while I capture the actual user input.
I found a module in the standard library called getpass, but it doesn't echo anything while the user inputs the password (similar to Linux behavior).
The getpass module is written in Python. You could easily modify it to do this. In fact, here is a modified version of getpass.win_getpass() that you could just paste into your code:
import sys
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
msvcrt.putch('\b')
else:
pw = pw + c
msvcrt.putch("*")
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
You might want to reconsider this, however. The Linux way is better; even just knowing the number of characters in a password is a significant hint to someone who wants to crack it.