Reputation: 35750
I'm writing a console program with Python under Windows.
The user need to login to use the program, when he input his password, I'd like they to be echoed as "*", while I can get what the user input.
I found in the standard library a module called getpass, but it will not echo anything when you input(linux like).
Thanks.
Upvotes: 9
Views: 10305
Reputation: 2173
kindall's answer is close, but it has issues with backspace not erasing the asterisks, as well as backspace being able to go back beyond the input prompt.
Try:
def win_getpass(prompt='Password: ', stream=None):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return fallback_getpass(prompt, stream)
import msvcrt
for c in prompt:
msvcrt.putwch(c)
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
if pw == '':
pass
else:
pw = pw[:-1]
msvcrt.putwch('\b')
msvcrt.putwch(" ")
msvcrt.putwch('\b')
else:
pw = pw + c
msvcrt.putwch("*")
msvcrt.putwch('\r')
msvcrt.putwch('\n')
return pw
Note mscvrt.putwch does not work with python 2.x, you need to use mscvrt.putch instead.
Upvotes: 5
Reputation: 184280
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.
Upvotes: 8
Reputation:
You can use the getpass
module. This doesn't exactly answer the question because the getpass function doesn't output anything to the console except for the prompt. The reason for this is that it's an extra layer of security. If someone is watching over your shoulder, they won't be able to figure out how long your password is.
Here's an example of how to use it:
from getpass import getpass
getpass('Enter your password: ')
This example will display "Enter your password: " and then you can type in your password.
Upvotes: -1