您知道在 Linux 中,当您尝试一些 Sudo 内容时,它会告诉您输入密码,并且当您键入时,终端窗口中没有显示任何内容(未显示密码)?
有没有办法在 Python 中做到这一点?我正在编写一个需要如此敏感信息的脚本,并希望在我输入时将其隐藏。
换句话说,我想在不显示密码的情况下从用户那里获取密码。
from getpass import getpass
password = getpass()
可选提示可以作为参数传递;默认值为 "Password: "
。
请注意,此功能需要正确的终端,因此它可以关闭输入字符的回显 - 请参阅 “GetPassWarning: Can not control echo on the terminal” when running from IDLE 了解更多详细信息。
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(
<string>,sys.stderr)
此代码将打印一个星号而不是每个字母。
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 提供的代码的代码
特征:
适用于最多 64 个字符的密码
接受退格输入
输出 * 字符 (DEC: 42 ; HEX: 0x2A) 而不是输入字符
缺点:
仅适用于 Windows
函数 secure_password_input()
在调用时将密码作为 string
返回。它接受 Password Prompt 字符串,该字符串将显示给用户以输入密码
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
不定期副业成功案例分享
getpass()
背后的想法是,没有人可以通过阅读源代码来找到您的密码,并且没有人可以通过盯着您的肩膀并在您键入密码时从屏幕上读出您的密码来获取您的密码在。