Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
830 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 == '
' or c == '
':
            break
        if c == '03':
            raise KeyboardInterrupt
        if c == '':
            pw = pw[:-1]
            msvcrt.putch('')
        else:
            pw = pw + c
            msvcrt.putch("*")
    msvcrt.putch('
')
    msvcrt.putch('
')
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...