我正在设计一个Python命令行工具,它本质上是一些REST API的包装器。一般的想法是,用户无需离开终端即可进行远程更改。
我唯一不确定的细节是如何缓存用户凭据,这样他们每次拨打远程电话时都不必输入username
和password
。我担心当他们不使用该工具时会长时间暴露用户凭据。有没有一种典型的方法可以在没有编写文件的情况下执行此操作,并且在经过一段时间后创建一个销毁文件的线程?
答案 0 :(得分:1)
我建议使用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
使用原生平台的密钥环来存储凭据,我相信在N
时间过后,系统会再次提示您,但您必须阅读keyring
上的文档知道N
是什么。