How to have password echoed as asterisks

自作多情 提交于 2019-11-26 06:48:39

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/10990998/how-to-have-password-echoed-as-asterisks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!