我正在设计一个 Python 命令行工具,它本质上是一些 REST API 的包装器。总体思路是让用户无需离开终端即可进行远程更改。
我不太确定的唯一细节是如何缓存用户凭据,这样他们就不必在每次创建时都输入 username
和 password
远程调用。我担心在用户不使用该工具时,他们的凭据会长时间暴露在外。有没有一种典型的方法可以做到这一点,而无需写入文件并创建一个线程在经过特定时间后销毁文件?
最佳答案
我推荐使用 pypi 的 keyring
包,然后你可以用一些实用函数将它包装起来:
SERVICE_NAME = 'confluence_api'
def get_login_cli(username = None, prompt = False):
'''
Get the password for the username out of the keyring. If the password
isn't found in the keyring, ask for it from the command line.
'''
disp_username = False
if username is None or prompt:
username = getpass.getuser()
disp_username = True
passwd = keyring.get_password(SERVICE_NAME, username)
if passwd is None or prompt:
if disp_username:
print 'login: %s' % username
passwd = getpass.getpass()
set_password(username, passwd)
return (username, passwd)
def set_password(username, passwd):
'''
Writes the password to the keyring.
'''
keyring.set_password(SERVICE_NAME, username, passwd)
然后您的运行时脚本可以这样调用它:
username, passwd = get_login_cli(username, **kwargs)
print("username = %s" % (username))
所以登录后,密码会被缓存,不会提示第二次。 keyring
使用 native 平台的 key 环来存储凭据,我相信在 N
时间过去后,您会再次收到提示,但您必须阅读文档keyring
知道 N
是什么。
关于python - 缓存命令行工具的用户远程凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36341923/