从标准输入读取密码

问题:从标准输入读取密码

场景:一个交互式CLI Python程序,需要密码。这也意味着没有GUI解决方案。

在bash中,我无需重新输入密码即可在屏幕上输入密码

read -s

Python有类似的东西吗?即

password = raw_input('Password: ', dont_print_statement_back_to_screen)

替代方法:将键入的字符替换为“ *”,然后再将其发送回屏幕(又称浏览器样式)。

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


回答 0

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

回答 1

是的getpass:“不提示用户提示输入密码。”

编辑:我自己还没有玩过这个模块,所以这就是我刚准备的(不过,如果到处都找到类似的代码,不会感到惊讶):

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

(这是Python 3.x;使用raw_input而不是input使用Python2.x。)

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