Read password from stdin

瘦欲@ 提交于 2019-11-26 04:10:42

问题


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).


回答1:


>>> import getpass
>>> pw = getpass.getpass()



回答2:


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.)



来源:https://stackoverflow.com/questions/1761744/read-password-from-stdin

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