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.
while using getpass in python, nothing is indicated to show a password input. this can be resolved by this simple solution: just copy the 'getpass_ak.py' module provided in the link to python's Lib folder. this will add * to your password inputs.
There are various Python modules that are used to hide the user's inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With