Python中的 getpass() 和 getuser() (没有回显的密码)
getpass() 提示用户输入密码而不回显。 getpass 模块提供了一种安全的方式来处理程序通过终端与用户交互的密码提示。
该模块提供两个功能:
- 获取通行证()
getpass.getpass(prompt='Password: ', stream=None)
- getpass()函数用于使用字符串提示向用户提示,并从用户那里读取输入作为密码。输入读取默认为“密码:”作为字符串返回给调用者。
让我们通过一些示例来了解它的实现。
示例 1:调用者未提供提示
Python
# A simple Python program to demonstrate
# getpass.getpass() to read password
import getpass
try:
p = getpass.getpass()
except Exception as error:
print('ERROR', error)
else:
print('Password entered:', p)
Python
# A simple Python program to demonstrate
# getpass.getpass() to read security question
import getpass
p = getpass.getpass(prompt='Your favorite flower? ')
if p.lower() == 'rose':
print('Welcome..!!!')
else:
print('The answer entered by you is incorrect..!!!')
Python
# Python program to demonstrate working of
# getpass.getuser()
import getpass
user = getpass.getuser()
while True:
pwd = getpass.getpass("User Name : %s" % user)
if pwd == 'abcd':
print "Welcome!!!"
break
else:
print "The password you entered is incorrect."
- 在这里,调用者没有提供任何提示。因此,它被设置为默认提示“密码”。
输出 :
$ python3 getpass_example1.py
Password:
('Password entered:', 'aditi')
- 示例 2:安全问题
有些程序会询问安全问题,而不是询问密码以获得更好的安全性。在这里,提示可以更改为任何值。
Python
# A simple Python program to demonstrate
# getpass.getpass() to read security question
import getpass
p = getpass.getpass(prompt='Your favorite flower? ')
if p.lower() == 'rose':
print('Welcome..!!!')
else:
print('The answer entered by you is incorrect..!!!')
- 输出 :
$ python3 getpass_example2.py
Your favorite flower?
Welcome..!!!
$ python3 getpass_example2.py
Your favorite flower?
The answer entered by you is incorrect..!!!
- 获取用户()
获得通行证。获取用户()
getuser()函数显示用户的登录名。该函数依次检查环境变量 LOGNAME、USER、LNAME 和 USERNAME,并返回第一个非空字符串的值。
示例 3:
Python
# Python program to demonstrate working of
# getpass.getuser()
import getpass
user = getpass.getuser()
while True:
pwd = getpass.getpass("User Name : %s" % user)
if pwd == 'abcd':
print "Welcome!!!"
break
else:
print "The password you entered is incorrect."
- 输出 :
$ python3 getpass_example3.py
User Name : bot
Welcome!!!
$ python3 getpass_example3.py
User Name : bot
The password you entered is incorrect.