Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have password echoed as asterisks

I'm 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: * * * * * *).

Here's the code I have so far, and I can't figure out why it doesn't 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

Any help would be appreciated.

like image 604
zk-Jack Avatar asked Jun 12 '12 05:06

zk-Jack


People also ask

How do I convert a password into asterisks while it is being entered in Python?

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. Save this answer.

How Show password star in HTML?

See Passwords Behind Asterisk in Google ChromeWhen the HTML Editor opens, look for input type = “password” field and change “password” to “text” and press Enter to save. An easy way to find that line of code is to hit Ctrl + F and type: password in the search field and arrow to it. There you have it!

How do you mask a password in Python?

maskpass() maskpass() is a Python module that can be used to hide passwords of users during the input time.


1 Answers

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.

like image 145
David Wolever Avatar answered Oct 21 '22 16:10

David Wolever