Coder Perfect

Obtaining a password input that is hidden

Problem

When you try some Sudo stuff in Linux, it prompts you to input the password, but nothing appears in the terminal window as you type (the password isn’t shown)?

Is it possible to achieve that in Python? I’m working on a script that involves a lot of private information, and I’d like to keep it hidden as I type it.

In other words, I’d like to retrieve the user’s password without having to reveal it.

Asked by Nacht

Solution #1

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is “Password: “.

This function requires a good terminal to turn off echoing of typed text — for more information, see “GetPassWarning: Cannot control echo on the terminal” when running from IDLE.

Answered by Sven Marnach

Solution #2

import getpass

pswd = getpass.getpass('Password:')

getpass is compatible with Linux, Windows, and Mac.

Answered by Nafscript

Solution #3

Getpass can be used for this.

Answered by RanRag

Solution #4

Instead of each letter, this code will print an asterisk.

import sys
import msvcrt

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

print '\n'+passwor

Answered by Ahmed ALaa

Solution #5

@Ahmed ALaa’s response has been updated.

# import msvcrt
import getch

def getPass():
    passwor = ''
    while True:
        x = getch.getch()
        # x = msvcrt.getch().decode("utf-8")
        if x == '\r' or x == '\n':
            break
        print('*', end='', flush=True)
        passwor +=x
    return passwor

print("\nout=", getPass())

msvcrt is exclusively for Windows, however PyPI’s getch should work for both (I only tested with linux). To make it work for Windows, you simply comment or uncomment the two lines.

Answered by Mostafa Hassan

Post is based on https://stackoverflow.com/questions/9202224/getting-a-hidden-password-input