【发布时间】:2012-03-01 09:55:50
【问题描述】:
您知道在 Linux 中,当您尝试一些 Sudo 内容时,它会告诉您输入密码,而当您键入时,终端窗口中没有显示任何内容(未显示密码)?
有没有办法在 Python 中做到这一点?我正在编写一个需要如此敏感信息的脚本,并希望在我输入时将其隐藏。
换句话说,我想在不显示密码的情况下从用户那里获取密码。
【问题讨论】:
标签: python passwords user-input
您知道在 Linux 中,当您尝试一些 Sudo 内容时,它会告诉您输入密码,而当您键入时,终端窗口中没有显示任何内容(未显示密码)?
有没有办法在 Python 中做到这一点?我正在编写一个需要如此敏感信息的脚本,并希望在我输入时将其隐藏。
换句话说,我想在不显示密码的情况下从用户那里获取密码。
【问题讨论】:
标签: python passwords user-input
from getpass import getpass
password = getpass()
一个可选的提示可以作为参数传递;默认为"Password: "。
请注意,此功能需要正确的终端,因此它可以关闭输入字符的回显 - 请参阅 “GetPassWarning: Can not control echo on the terminal” when running from IDLE 了解更多详细信息。
【讨论】:
getpass() 背后的想法是,没有人可以通过阅读源代码来查看您的密码,并且没有人可以通过盯着您的肩膀并在您输入密码时从屏幕上读出您的密码来获取您的密码在。
import getpass
pswd = getpass.getpass('Password:')
getpass 适用于 Linux、Windows 和 Mac。
【讨论】:
Warning (from warnings module): File "C:\Python27\lib\getpass.py", line 92 return fallback_getpass(prompt, stream) GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed. ,但在命令提示符下运行良好,找到原因here
import sys):getpass.getpass(,sys.stderr)为此使用getpass。
getpass.getpass - 提示用户输入密码而不回显
【讨论】:
此代码将打印一个星号而不是每个字母。
import sys
import msvcrt
passwor = ''
while True:
x = msvcrt.getch()
if x == '\r':
break
sys.stdout.write('*')
passwor +=x
print '\n'+passwor
【讨论】:
getpass 答案。不错
更新@Ahmed ALaa 的答案
# 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 us 仅适用于 Windows,但来自 PyPI 的 getch 应该适用于两者(我只用 linux 测试过)。 您还可以注释/取消注释这两行以使其适用于 windows。
【讨论】:
这是我基于 @Ahmed ALaa
提供的代码的代码特点:
* 字符 (DEC: 42 ; HEX: 0x2A) 而不是输入字符缺点:
函数secure_password_input() 在调用时将密码作为string 返回。它接受一个密码提示字符串,将显示给用户输入密码
def secure_password_input(prompt=''):
p_s = ''
proxy_string = [' '] * 64
while True:
sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
c = msvcrt.getch()
if c == b'\r':
break
elif c == b'\x08':
p_s = p_s[:-1]
proxy_string[len(p_s)] = " "
else:
proxy_string[len(p_s)] = "*"
p_s += c.decode()
sys.stdout.write('\n')
return p_s
【讨论】: