How to have password echoed as asterisks

2020-01-24 13:55发布

I am trying to figure out how to prompt for a password, and have the users input echoed back as asterisks (********)

So recently, I took on the project of creating a remote server that could be connected to using the socket module in Python. It's not yet done, as I am in the process of making the console used to connect to the server.

I am trying make a login window where a user is prompted to enter their Username and Password, although when the password is entered I am looking for asterisks to be printed, like common password entry (i.e. - Sekr3t is echo'd as: * * * * * *).

After days of research on it, I am nearly done yet there is still a last error that is driving me insane (I am completely unable to solve it). Note - I know there is a getpass module that could be used to replace this, with much greater ease, but nothing echo'd isn't exactly what I'm looking for.

Here's the password login code I have so far, and I cannot figure out why it does not echo asterisks:

import msvcrt
import sys

def login(prompt = '> '):
   write = sys.stdout.write

   for x in prompt:
       msvcrt.putch(x)
   passw = ""

   while 1:
       x = msvcrt.getch()
       if x == '\r' or x == '\n':
           break
       if x == '\b':
           # position of my error
           passw = passw[:-1]
       else:
           write('*')
           passw = passw + x
   msvcrt.putch('\r')
   msvcrt.putch('\n')
   return passw

>

If you read through the code and/or ran it through something like IDLE, you might notice that when the user back-space's, the stored data is erased by one character, but the asterisks printed aren't. i.e. - Sekr3t + backspace = Sekr3, yet * * * * * * is left echo'd. Any help on how to erase the last asterisk when backspace is enter'd would be greatly appreciated. Also note, a lot of this code was from the getpass module. I know it's not that great of an explanation, and probably not that great of code but I'm still learning -- please bear with me.

2条回答
劳资没心,怎么记你
2楼-- · 2020-01-24 14:10

I think this way is very simple and effective

import sys
import msvcrt

passwor = ''
while True:
    x = msvcrt.getch()
    if x == '\r':
        break
    sys.stdout.write('*')
    passwor +=x

print '\n'+passwor
查看更多
在下西门庆
3楼-- · 2020-01-24 14:17

You should be able to erase an asterisk by writing the characters \x08 \x08. The \x08 will move the cursor back one position, the space will overwrite the asterisk, then the last \x08 will move the cursor back again, putting it in the correct position to write the next *.

I don't know off the top of my head how to determine when a backspace is typed, but you can do that easily: just add something like print repr(x) after you've called x = msvcrt.getch(), then start your program and hit backspace.

查看更多
登录 后发表回答