Masking user input in python with asterisks

I am trying to mask what the user enters into IDLE with asterisks, so the people around them cannot see what they typed / typed. I use the main source input to collect what they are typing.

key = raw_input('Password :: ') 

Ideal IDLE hint after entering user password:

 Password :: ********** 
+7
source share
4 answers

Depending on the OS, how you get one character from user input and how to check for carriage returns will vary.

See this post: Python reads one character from the user

In OSX, for example, you can do something like this:

 import sys, tty, termios def getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch key = "" sys.stdout.write('Password :: ') while True: ch = getch() if ch == '\r': break key += ch sys.stdout.write('*') print print key 
+2
source

To solve this problem, I wrote this small pyssword module to mask the user input password on the command line. It works with windows. Code below:

 from msvcrt import getch import getpass, sys def pyssword(prompt='Password: '): ''' Prompt for a password and masks the input. Returns: the value entered by the user. ''' if sys.stdin is not sys.__stdin__: pwd = getpass.getpass(prompt) return pwd else: pwd = "" sys.stdout.write(prompt) sys.stdout.flush() while True: key = ord(getch()) if key == 13: #Return Key sys.stdout.write('\n') return pwd break if key == 8: #Backspace key if len(pwd) > 0: # Erases previous character. sys.stdout.write('\b' + ' ' + '\b') sys.stdout.flush() pwd = pwd[:-1] else: # Masks user input. char = chr(key) sys.stdout.write('*') sys.stdout.flush() pwd = pwd + char 
+2
source

If you need a solution that works on Windows / macOS / Linux and Python 2 and 3, you can install the stdiomask module:

 pip install stdiomask 

Unlike getpass.getpass() (which is located in the Python standard library), the stdiomask module can display *** mask characters with stdiomask .

Usage example:

 >>> stdiomask.getpass() Password: ********* 'swordfish' >>> stdiomask.getpass(mask='X') # Change the mask character. Password: XXXXXXXXX 'swordfish' >>> stdiomask.getpass(prompt='PW: ', mask='*') # Change the prompt. PW: ********* 'swordfish' >>> stdiomask.getpass(mask='') # Don't display anything. Password: 'swordfish' 

More information at https://pypi.org/project/stdiomask/

+2
source

Disclaimer: does not provide an asterisk in the terminal, but it does in a jupyter laptop.

The code below replaces the written characters with an asterisk and allows you to delete incorrectly entered characters. The number of stars reflects the number of characters typed.

 import getpass key = getpass.getpass('Password :: ') 

enter image description here

And after the user presses the input:

enter image description here

0
source

Source: https://habr.com/ru/post/1209811/


All Articles