188

Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.

In bash I could get a password read in without re-prompting it on screen via

read -s

Is there something similar for Python? I.e.,

password = raw_input('Password: ', dont_print_statement_back_to_screen)

Alternative: Replace the typed characters with '*' before sending them back to screen (aka browser' style).

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Boldewyn
  • 81,211
  • 44
  • 156
  • 212

2 Answers2

297
>>> import getpass
>>> pw = getpass.getpass()
mjv
  • 73,152
  • 14
  • 113
  • 156
  • 4
    Yeah, them batteries. ;-) One of the cool thing with Python is its ability to bind easily with binaries in other language, in particular C, hence leveraging a lot of existing stuff (such as getpass(), I believe) – mjv Nov 19 '09 at 08:35
  • 2
    Even better, getpass() deals with the situation in which a CLI tool is being fed data via STDIN and yet you want the ability to type the password yourself. Great tool! – Tiemen Jul 22 '13 at 21:00
  • 2
    @Tiemen but I came here looking for a solution to do this because getpass() is still prompting me and waiting for a password even though I piped the password to my script – Michael Dec 21 '13 at 21:30
  • 1
    For me, getpass poppoed up a window (not what I wanted, nor what its help said) and didn't obscure the password when I typed it in! Code to reproduce: import getpass; getpass.getpass() – Michael Grazebrook Sep 16 '14 at 16:22
  • @Tiemen IIRC, unix tools support that by re-opening the stderr stream for reading, instead of for writing. It's a neat hack, yeah? – jpaugh Sep 17 '16 at 16:46
  • 2
    but this doesn't display '*' as one types. How does one achieve this? – Jason Nov 17 '17 at 05:27
  • @Jason you don't want that – OrangeDog Sep 22 '21 at 09:59
55

Yes, getpass: "Prompt the user for a password without echoing."

Edit: I had not played with this module myself yet, so this is what I just cooked up (wouldn't be surprised if you find similar code all over the place, though):

import getpass

def login():
    user = input("Username [%s]: " % getpass.getuser())
    if not user:
        user = getpass.getuser()

    pprompt = lambda: (getpass.getpass(), getpass.getpass('Retype password: '))

    p1, p2 = pprompt()
    while p1 != p2:
        print('Passwords do not match. Try again')
        p1, p2 = pprompt()

    return user, p1

(This is Python 3.x; use raw_input instead of input when using Python 2.x.)

Stephan202
  • 59,965
  • 13
  • 127
  • 133