6

我正在与一位同事一起开发一个涉及连接到数据库的脚本。我们希望保持代码独立于我们中的哪个人使用它,同时保持我们的密码私密,并且不必在工作日一遍又一遍地进行身份验证。经过一番搜索(我们都是 Python 新手),似乎我们可以为此目的使用密钥环,所以我从 pip 安装了它(根据我对安装日期的记忆,很可能是库的 1.2.2 版本)。

问题是,当我尝试访问存储的密码时,系统会提示我设置主密码以访问密钥环,如下所示(来自 IDLE):

>>> import keyring
>>> keyring.set_password('Service', 'MyUsername', 'MyPassword')

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.
Please enter password for encrypted keyring:

设置密码后,我可以轻松获取和设置密码,直到我重新启动 shell。现在我必须再次输入主密码:

>>> ================================ RESTART ================================
>>> import keyring
>>> print keyring.get_password('Service', 'MyUsername')

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.
Please enter password for encrypted keyring:

输入主密码后,此身份验证仅在当前会话期间/重新启动之间持续存在。从命令行运行脚本时,情况更糟——每次运行脚本时我都必须进行身份验证。在这一点上,密钥环并没有为我节省任何时间或精力,我怀疑它是否让我的密码比记忆和手动输入更安全。

搜索解决方案后,如果主密码与用户帐户的密码相同,似乎密钥环会在 Unix 上自动进行身份验证,但这在 Windows 上对我不起作用。

我是否试图让密钥环做一些它不应该做的事情,或者我的实现中只是有一个错误?

我的经验似乎与另一位声称在应用程序尝试访问相关问题中的密钥环时没有提示输入密码的用户报告的经验相冲突,python-keyring 如何在 Windows 上工作?

4

1 回答 1

2

您使用的是哪个后端?检查使用:

>>> from keyring import get_keyring
>>> get_keyring()
[... what is output here?]

如果它输出这个:

<keyring.backends.file.EncryptedKeyring object at 0x.....>

这就是它要求密码的原因。该模块未能找到要使用的任何特定于平台的密钥环,因此它只是使用主密码加密您的密码并将它们放入普通文件中。

就我个人而言,我的脚本在无人看管的情况下运行比我的密码安全更重要,所以我编写了这个函数:

def configureKeyring():
    """
    EncryptedKeyring requires a master password to unlock it, which is not ideal
    for our scripts since we want them to run unattended. So if we're using
    EncryptedKeyring, automatically swap to a PlaintextKeyring instead.

    If we're using something else, say WinVaultKeyring, then that's more secure
    than PlaintextKeyring without being any less convenient, so we'll use it.
    """
    from keyring               import get_keyring, set_keyring
    from keyring.backends.file import EncryptedKeyring, PlaintextKeyring

    if isinstance(get_keyring(), EncryptedKeyring):
        set_keyring(PlaintextKeyring())

在使用keyringtoset_password或之前get_password,请运行此功能configureKeyring(),如果您像我一样重视不需要插入主密码而不是保持密码安全。在执行此操作之前,请了解您以明文形式存储密码的安全隐患。

一个更好的长期解决方案可能是调查所有其他可用的后端并安装适当的 pre-reqs 以便可以使用不同的 pre-reqs,如果存在不需要输入主密码并且只需登录的地方是充足的。

注意:来自https://build.opensuse.org/package/view_file/openSUSE:Leap:42.2/python-keyring/python-keyring.changes?rev=a2e727a9e4a21a65c9496362d8cff27d

随着这些密钥环的移动,配置中明确指出的任何密钥环都需要更新以替换“keyring.backends”。使用“keyrings.alt.”。例如,“keyring.backends.file.PlaintextKeyring”变为“keyrings.alt.file.PlaintextKeyring”

因此,根据已提供的解决方案中的版本,您可能必须这样做

from keyrings.alt.file import EncryptedKeyring, PlaintextKeyring 
于 2015-09-28T15:34:56.567 回答