你知道如何在Linux中尝试一些Sudo的东西,它告诉你输入密码,当你输入时,终端窗口中没有显示任何内容(密码没有显示)?
有没有办法在Python中做到这一点?我正在编写一个需要如此敏感信息的脚本,并希望在我输入时隐藏它。
换句话说,我想从用户那里获取密码而不显示密码。
答案 0 :(得分:234)
password = getpass()
可选的提示可以作为参数传递;默认值为"Password: "
。
请注意,此功能需要正确的终端,因此可以关闭键入字符的回显 - 有关详细信息,请参阅“GetPassWarning: Can not control echo on the terminal” when running from IDLE。
答案 1 :(得分:149)
import getpass
pswd = getpass.getpass('Password:')
getpass适用于Linux,Windows和Mac。
答案 2 :(得分:26)
为此目的使用getpass。
getpass.getpass - 提示用户输入密码而不回显
答案 3 :(得分:11)
<script src="https://d3js.org/d3.v3.min.js"></script>
此代码将打印星号而不是每个字母。
答案 4 :(得分:2)
更新@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仅适用于Windows,但PyPI的getch应该同时适用于两者(我仅在linux上进行过测试)。 您也可以注释/取消注释这两行,以使其适用于Windows。
答案 5 :(得分:0)
这是基于 @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
答案 6 :(得分:-1)
#!/usr/bin/python3
from getpass import getpass
passwd = getpass("password: ")
print(passwd)