我有一个小Bash脚本,我用它来访问twitter,并在某些情况下弹出咆哮通知。用脚本存储密码的最佳方法是什么?

I would like to commit this script to the git repo and make it available on GitHub, but I'm wondering what the best way to keep my login/password private while doing this is. Currently, the password is stored in the script itself. I can't remove it right before I push because all the old commits will contain the password. Developing without a password isn't an option. I imagine that I should be storing the password in an external config file, but I thought I'd check to see if there was an established way to handle this before I tried and put something together.


当前回答

Is there any possibility to tell github to track the file under a different name? Example: Locally, I have a file passwords.config with real passwords, and sample-passwords.config with stubs. However, in public repo, I'd like to have only passwords.config with content from sample-passwords.config and real passwords.config ignored. I know .gitignore, which can hide my passwords.config, but I don't know is there any solution to rename sample-passwords.config while commiting to remote public repo. Of course, I'd like to avoid situation, when my local repo tracks renamed file as if something changed in git status.

其他回答

一种方法是使用环境变量设置密码(或API密钥)。 所以这个密码不受修改控制。

使用Bash,您可以使用来设置环境变量

export your_env_variable='your_password'

这种方法可以与Travis这样的持续集成服务一起使用,你存储在GitHub存储库中的代码(没有密码)可以由Travis执行(使用环境变量设置你的密码)。

使用Bash,你可以使用以下命令获取环境变量的值:

echo "$your_env_variable"

使用Python,你可以使用以下命令获取环境变量的值:

import os
print(os.environ['your_env_variable'])

PS:请注意这可能有点风险(但这是一种相当常见的做法)https://www.bleepingcomputer.com/news/security/javascript-packages-caught-stealing-environment-variables/

PS2:这篇题为“如何安全地存储API密钥”的dev.to文章可能会很有趣。

Greg说的,但我想补充的是,签入文件foobar.config-TEMPLATE是个好主意。

它应该包含示例名称、密码或其他配置信息。那就很明显什么才是真正的傻瓜了。Config应该包含,而不必查看所有必须在foobar中显示的值的代码。配置和格式。

通常配置值可以是不明显的,如数据库连接字符串和类似的东西。

信任,但要核实。

在.gitignore中,这将从repo中排除一个“安全”目录:

secure/

但我和迈克尔·波特一样偏执。因此,为了验证.gitignore,这里有一个Python单元测试,如果这个“安全”目录被签入,它将发出一个喇叭。为了检查检查,也要测试一个合法的目录:

def test_github_not_getting_credentials(self):
    safety_url = 'https://github.com/BobStein/fliki/tree/master/static'
    danger_url = 'https://github.com/BobStein/fliki/tree/master/secure'

    self.assertEqual(200, urllib.request.urlopen(safety_url).status)

    with self.assertRaises(urllib.error.HTTPError):
        urllib.request.urlopen(danger_url)

实现这一点的典型方法是从配置文件中读取密码信息。如果你的配置文件叫做foobar。Config,然后向存储库提交一个名为foobar.config.example的文件,其中包含示例数据。要运行程序,需要创建一个名为foobar的本地(不跟踪)文件。配置您的真实密码数据。

要从以前的提交中过滤出您现有的密码,请参阅GitHub删除敏感数据的帮助页面。

下面是我使用的一个技巧:

我在我的主文件夹中创建了一个名为: config

在这个文件夹中,我放置了我想外部化密码和密钥的任何数量的配置文件。

我通常使用反向域名语法,例如:

com.example.databaseconfig

然后在bash脚本中我这样做:

#!/bin/bash
source $HOME/.config/com.example.databaseconfig ||exit 1

|| exit 1如果无法加载配置文件,将导致脚本退出。

我在bash、python和ant脚本中使用了这种技术。

我很偏执,认为.gitignore文件不够健壮,无法防止无意签入。此外,没有任何监控机制,所以即使发生了签入,也没有人会发现如何处理它。

如果一个特定的应用程序需要一个以上的文件,我创建子文件夹而不是一个单一的文件。