为什么 git 在 Windows 下记不住我的密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/370030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 05:52:15  来源:igfitidea点击:

Why git can't remember my passphrase under Windows

windowsgitsshcmd

提问by Nesizer

I have just start using git and i can't get it to remember my passphrase I'm using cmd.exe elevated and my git host is github and i have create a ssh key like that guide on github

我刚刚开始使用 git,我无法记住我的密码我正在使用 cmd.exe 提升,我的 git 主机是 github,我在 github 上创建了一个类似于该指南的 ssh 密钥

but i still get

但我仍然得到

*\subnus.mvc>git push origin master
Enter passphrase for key '/c/Users/Subnus/.ssh/id_rsa':

回答by RobertB

I realize that this question is coming up on two years old, but I had the same issue and several answers here did not completely answer the question for me. Here is two step-by-step solutions, depending on whether you use TortoiseGit in addition to msysgit or not.

我意识到这个问题已经两年了,但我遇到了同样的问题,这里的几个答案并没有完全回答我的问题。这里有两个循序渐进的解决方案,这取决于除了 msysgit 之外你是否还使用 TortoiseGit。

First solutionAssumes Windows, msysgit, and PuTTY.

第一个解决方案假设使用 Windows、msysgit 和 PuTTY。

  1. Install msysgit and PuTTY as instructed.
  2. (Optional) Add PuTTY to your path. (If you do not do this, then any references to PuTTY commands below must be prefixed with the full path to the appropriate executable.)
  3. If you have not done so already, then generate a key hash as instructed at GitHub or as instructed by your Git host.
  4. Again, if you have not already done so, convert your key for use with PuTTY's pageant.exe using puttygen.exe. Instructions are in PuTTY's documentation, in this helpful guide, and several other places in cyberspace.
  5. Run PuTTY's pageant.exe, open your .ppk file ("Add Key"), and provide your passphrase for your key.
  6. Access Windows' environment variables dialog (Right-click on "Computer", Click on "Properties", Click on "Advanced system settings" or the "Advanced" tab, click on "Environment Variables"). Add the following environment variable:

    GIT_SSH=C:\full\path\to\plink.exe

    Replace "C:\full\path\to" with the full installation path to PuTTY, where plink.exe is found. It is probably best to add it to the "User variables" section. Also, make sure that the path you use to plink.exe matches the path you use for Pageant (pageant.exe). In some cases you may have several installations of PuTTY because it might be installed along with other applications. Using plink.exe from one installation and pageant.exe from another will likely cause you trouble.

  7. Open a command prompt.

  8. If you are trying to connect to a git repository hosted at Github.com then run the following command:

    plink.exe [email protected]

    If the git repository you are trying to connect to is hosted somewhere else, then replace [email protected]with an appropriate user name and URL. (Assuming Github) You should be informed that the server's host key is not cached, and asked if you trust it. Answer with a y. This will add the server's host key to PuTTY's list of known hosts. Without this step git commands will not work properly. After hitting enter, Github informs you that Github does not provide shell access. That's fine...we don't need it. (If you are connecting to some other host, and it gives you shell access, it is probably best to terminate the link without doing anything else.)

  9. All done! Git commands should now work from the command line. You may want to have pageant.exe load your .ppk file automatically at boot time, depending on how often you'll be needing it.
  1. 按照说明安装 msysgit 和 PuTTY。
  2. (可选)将 PuTTY 添加到您的路径中。(如果您不这样做,则下面对 PuTTY 命令的任何引用都必须以相应可执行文件的完整路径为前缀。)
  3. 如果您还没有这样做,请按照 GitHub 上的说明或您的 Git 主机的说明生成密钥哈希。
  4. 同样,如果您还没有这样做,请使用puttygen.exe转换您的密钥以与 PuTTY 的 pageant.exe 一起使用。说明位于 PuTTY 的文档、本实用指南以及网络空间的其他几个地方。
  5. 运行 PuTTY 的pageant.exe,打开您的 .ppk 文件(“添加密钥”),并为您的密钥提供密码。
  6. 访问 Windows 的环境变量对话框(右键单击“计算机”,单击“属性”,单击“高级系统设置”或“高级”选项卡,单击“环境变量”)。添加以下环境变量:

    GIT_SSH=C:\full\path\to\plink.exe

    将“C:\full\path\to”替换为 PuTTY 的完整安装路径,其中找到 plink.exe。最好将其添加到“用户变量”部分。此外,请确保用于 plink.exe 的路径与用于 Pageant (pageant.exe) 的路径匹配。在某些情况下,您可能安装了多个 PuTTY,因为它可能与其他应用程序一起安装。使用一个安装中的 plink.exe 和另一个安装中的 pageant.exe 可能会给您带来麻烦。

  7. 打开命令提示符。

  8. 如果您尝试连接到 Github.com 上托管的 git 存储库,请运行以下命令:

    plink.exe [email protected]

    如果您尝试连接的 git 存储库托管在其他地方,则将[email protected]替换为适当的用户名和 URL。(假设 Github)您应该被告知服务器的主机密钥未缓存,并询问您是否信任它。回答y。这会将服务器的主机密钥添加到 PuTTY 的已知主机列表中。如果没有这一步,git 命令将无法正常工作。按回车后,Github 会通知您 Github 不提供 shell 访问。没关系……我们不需要它。(如果您正在连接到某个其他主机,并且它为您提供 shell 访问权限,那么最好终止链接而不做任何其他事情。)

  9. 全部完成!Git 命令现在应该可以从命令行运行。您可能希望 pageant.exe在启动时自动加载您的 .ppk 文件,具体取决于您需要它的频率。

Second solutionAssumes Windows, msysgit, and TortoiseGit.

第二种解决方案假设使用 Windows、msysgit 和 TortoiseGit。

TortoiseGit comes with PuTTY executables, and a specially modified version of plink (called TortoisePlink.exe) that will make things easier.

TortoiseGit 带有 PuTTY 可执行文件,以及一个经过特殊修改的 plink(称为 TortoisePlink.exe),这将使事情变得更容易。

  1. Install msysgit and TortoiseGit as instructed.
  2. If you have not done so already, then generate a key hash as instructed at GitHub or as instructed by your Git host.
  3. Again, if you have not already done so, convert your key for use with TortoiseGit's pageant.exe using TortoiseGit's puttygen.exe. Instructions are in PuTTY's documentation, in the helpful guide linked to in the first solution, and several other places in cyberspace.
  4. Run TortoiseGit's pageant.exe, open your .ppk file ("Add Key"), and provide your passphrase for your key.
  5. Access Windows' environment variables dialog (Right-click on "Computer", Click on "Properties", Click on "Advanced system settings" or the "Advanced" tab, click on "Environment Variables"). Add the following environment variable:

    GIT_SSH=C:\full\path\to\TortoisePlink.exe

    Replace "C:\full\path\to" with the full installation path to TortoiseGit, where TortoisePlink.exe is found. It is probably best to add it to the "User variables" section. Also, make sure that the path you use to TortoisePlink.exe matches the path you use for Pageant (pageant.exe). In some cases you may have several installations of PuTTY because it might be installed along with other applications. Using TortoisePlink.exe from the TortoiseGit installation and pageant.exe from another installation of a different application (or from a standalone PuTTY installation) will likely cause you trouble.

  6. All done! Git commands should now work from the command line. The first time you try to connect to your git repository you will probably be informed that the server's host key is not cached, and asks if you trust the server. Click on "Yes". (This is TortoisePlink.exe in action.)

    You may want to have pageant.exe load your .ppk file automatically at boot time, depending on how often you'll be needing it.

  1. 按照说明安装 msysgit 和 TortoiseGit。
  2. 如果您还没有这样做,请按照 GitHub 上的说明或您的 Git 主机的说明生成密钥哈希。
  3. 同样,如果您还没有这样做,请使用 TortoiseGit 的puttygen.exe转换您的密钥以与 TortoiseGit 的 pageant.exe 一起使用。说明位于 PuTTY 的文档、链接到第一个解决方案的有用指南以及网络空间的其他几个地方。
  4. 运行 TortoiseGit 的pageant.exe,打开您的 .ppk 文件(“添加密钥”),并为您的密钥提供密码。
  5. 访问 Windows 的环境变量对话框(右键单击“计算机”,单击“属性”,单击“高级系统设置”或“高级”选项卡,单击“环境变量”)。添加以下环境变量:

    GIT_SSH=C:\full\path\to\TortoisePlink.exe

    将“C:\full\path\to”替换为 TortoiseGit 的完整安装路径,其中 TortoisePlink.exe 位于其中。最好将其添加到“用户变量”部分。此外,请确保用于 TortoisePlink.exe 的路径与用于 Pageant (pageant.exe) 的路径匹配。在某些情况下,您可能安装了多个 PuTTY,因为它可能与其他应用程序一起安装。使用 TortoiseGit 安装中的 TortoisePlink.exe 和不同应用程序的另一个安装(或独立 PuTTY 安装)中的 pageant.exe 可能会给您带来麻烦。

  6. 全部完成!Git 命令现在应该可以从命令行运行。第一次尝试连接到 git 存储库时,您可能会被告知服务器的主机密钥未缓存,并询问您是否信任该服务器。单击“是”。(这是正在运行的 TortoisePlink.exe。)

    您可能希望 pageant.exe在启动时自动加载您的 .ppk 文件,具体取决于您需要它的频率。

Third solutionAssumes Window, msysgit, and native command prompt.

第三种解决方案假定使用 Window、msysgit 和本机命令提示符。

  1. Install msysgit
  2. Make sure to allow git to be used on the MS-DOS command prompt
  3. Run start-ssh-agent
  4. Enter SSH passphrases
  5. All done! Git commands should now work in the native command prompt.
  1. 安装 msysgit
  2. 确保允许在 MS-DOS 命令提示符下使用 git
  3. start-ssh-agent
  4. 输入 SSH 密码
  5. 全部完成!Git 命令现在应该在本机命令提示符下工作。

回答by Franz

For anybody needing more detailed instructions, see this page: http://help.github.com/working-with-key-passphrases/

对于需要更详细说明的任何人,请参阅此页面:http: //help.github.com/working-with-key-passphrases/

回答by Guy Avraham

In case you are using Git bashunder Windowsyou can perform the following:

如果您在Windows下使用Git bash,您可以执行以下操作:

eval `ssh-agent -s`
ssh-add ~/.ssh/*_rsa

it will ask for pass phrase in the second command, and that's it. Each additional action you will need to do (which once required pass phrase) won't ask you for the pass phrase (see an example in the screen shot below):

它会在第二个命令中要求输入密码,仅此而已。您需要执行的每个附加操作(曾经需要密码短语)都不会要求您输入密码短语(请参阅下面屏幕截图中的示例):

adding pass phrase in Git bash on Windows

在 Windows 上的 Git bash 中添加密码短语

回答by d3r3kk

Every time I set up a new desktop I forget these instructions, so I'm adding another answer here since I stumble across it equally often!

每次我设置一个新桌面时,我都会忘记这些说明,所以我在这里添加另一个答案,因为我同样经常偶然发现它!



Quick Steps for Impatient Users Like Me

像我这样没有耐心的用户的快速步骤

  1. Enable the OpenSSH Authentication Agentservice and make it start automatically.
  2. Add your SSH key to the agent with ssh-addon the command line.
  3. Test git integration, if it still asks for your passphrase, continue on.
  4. Add the environment variable $ENV:GIT_SSH=C:\Windows\System32\OpenSSH\ssh.exeto your session, or permanently to your user environment.
  1. 启用该OpenSSH Authentication Agent服务并使其自动启动。
  2. 使用ssh-add命令行将您的 SSH 密钥添加到代理。
  3. 测试 git 集成,如果它仍然要求您输入密码,请继续。
  4. 将环境变量添加$ENV:GIT_SSH=C:\Windows\System32\OpenSSH\ssh.exe到您的会话,或永久添加到您的用户环境。


Detailed Steps: Overview

详细步骤:概述

Windows has been shipping with OpenSSH for some time now.It includes all the necessary bits for ssh to work alongside Git, but it still seems to need some TLC before it works 100% seamlessly. Here's the steps I've been following with success as of Windows ver 10.0.18362.449 (you can see your Windows 10 version by opening a cmd.exe shell and typing ver).

Windows 已经随 OpenSSH 一起发布了一段时间。它包括 ssh 与 Git 一起工作的所有必要部分,但在 100% 无缝工作之前,它似乎仍然需要一些 TLC。以下是我在 Windows 版本 10.0.18362.449 中成功遵循的步骤(您可以通过打开 cmd.exe shell 并键入 来查看您的 Windows 10 版本ver)。

I assume here that you already have your SSH key setup, and is located at ~/.ssh/id_rsa

我在这里假设您已经设置了 SSH 密钥,并且位于 ~/.ssh/id_rsa

Enable the ssh-agent service on your Windows 10 box.

在 Windows 10 机器上启用 ssh-agent 服务。

  1. Start-> Type 'Services' and click on the Services App that appears.
  2. Find the OpenSSH Authentication Agentservice in the list.
  3. Right-click on the OpenSSH Authentication Agentservice, and choose 'Properties'.
  4. Change the Startup type:to Automatic.
  5. Click the Startbutton to change the service status to Running.
  6. Dismiss the dialog by clicking OK, and close the Services app.
  1. 开始-> 键入“服务”,然后单击出现的服务应用程序。
  2. OpenSSH Authentication Agent在列表中找到服务。
  3. 右键单击该OpenSSH Authentication Agent服务,然后选择“属性”。
  4. 将 更改Startup type:Automatic
  5. 单击Start按钮将服务状态更改为Running
  6. 单击 关闭对话框OK,然后关闭服务应用程序。

Add your key to the ssh-agent

将您的密钥添加到 ssh-agent

  1. Open your shell of preference (I'll use Windows Powershell in this example, applies to Powershell Core too).
  2. Add your SSH key to the ssh-agent: ssh-add(you can add the path to your key as the first argument if it differs from the default).
  3. Enter your passphrase if/when prompted to do so.
  1. 打开您的首选外壳(在此示例中我将使用 Windows Powershell,也适用于 Powershell Core)
  2. 将您的 SSH 密钥添加到ssh-agent:(ssh-add如果与默认值不同,您可以将密钥的路径添加为第一个参数)
  3. 如果/当提示这样做时,请输入您的密码。

Try Git + SSH

尝试 Git + SSH

  1. Open your shell (again, I'm using Powershell)and clone a repo. git clone [email protected]:octocat/Spoon-Knife
  2. If you see this prompt, continue on to the next section:
  1. 打开你的外壳(同样,我使用的是 Powershell)并克隆一个 repo。git clone [email protected]:octocat/Spoon-Knife
  2. 如果您看到此提示,请继续下一部分:
Enter passphrase for key '/c/Users/your_user_name/.ssh/id_rsa':

Set your GIT_SSHEnvironment Variable

设置GIT_SSH环境变量

In any session you can simply set this environment variable and the prompt for your passphrase will stop coming up and ssh will use the ssh-agenton your behalf. Alternatively, you can set your passphrase into your user's environment permanently.

在任何会话中,您只需设置此环境变量,密码短语的提示将停止出现,ssh 将ssh-agent代表您使用。或者,您可以将密码永久设置到用户的环境中。

To set GIT_SSHin the current shell only:

GIT_SSH仅在当前 shell 中设置:

  1. Open your shell of preference. (Powershell for me)
  2. Set the environment variable GIT_SSH to the appropriate ssh.exe: $Env:GIT_SSH=$((Get-Command -Name ssh).Source)
  3. Retry the steps in Try Git + SSHabove.
  1. 打开您喜欢的外壳。(对我来说是 Powershell)
  2. 将环境变量 GIT_SSH 设置为适当的ssh.exe$Env:GIT_SSH=$((Get-Command -Name ssh).Source)
  3. 重试上面尝试 Git + SSH 中的步骤。

To set GIT_SSHpermanently

GIT_SSH永久设置

  1. Open File Explorer. Start-> type 'File Explorer' and click on it in the list.
  2. Right-click 'This PC' and click on 'Properties'.
  3. Click on 'Advanced system settings'.
  4. Click the 'Environment Variables...' button.
  5. Under 'User variables for your_user_name' click New...
  6. Set Variable name:field to GIT_SSH
  7. Set the Variable value:field to path-to-ssh.exe (typically C:\Windows\System32\OpenSSH\ssh.exe).
  8. Click OK to dismiss the New User Variable dialog.
  9. Click OK to dismiss the Environment Variables dialog.
  10. Retry the steps in Try Git + SSHabove.
  1. 打开文件资源管理器。开始-> 键入“文件资源管理器”并在列表中单击它。
  2. 右键单击“此电脑”,然后单击“属性”。
  3. 单击“高级系统设置”。
  4. 单击“环境变量...”按钮。
  5. 在“your_user_name 的用户变量”下,单击新建...
  6. Variable name:字段设置为 GIT_SSH
  7. 将该Variable value:字段设置为 path-to-ssh.exe(通常为C:\Windows\System32\OpenSSH\ssh.exe)。
  8. 单击“确定”关闭“新建用户变量”对话框。
  9. 单击确定关闭环境变量对话框。
  10. 重试上面尝试 Git + SSH 中的步骤。


Note that this is likely going to change with new steps/procedures as Windows 10 progresses and as I learn more. I will attempt to keep this updated, I look forward to feedback in the comments.

请注意,随着 Windows 10 的发展和我了解更多信息,这可能会随着新的步骤/程序而改变。我会尽量保持更新,我期待评论中的反馈。

回答by Alex Essilfie

One extra solution 5 years, 8 months and 6 days after the question was posted wouldn't be a bad idea so here goes.

问题发布后 5 年 8 个月零 6 天的额外解决方案不会是一个坏主意,所以就这样吧。

NOTE:Assumes you are using a windows computer.

注意:假设您使用的是 Windows 计算机。

  1. Download the git-credential-winstore.
  2. Run it! If you have GIT in your PATHenvironment variable, it should just work. If you don't, run git-credential-winstore -i C:\Path\To\Git.exe.
  1. 下载git-credential-winstore
  2. 运行!如果您的PATH环境变量中有 GIT ,它应该可以正常工作。如果没有,请运行git-credential-winstore -i C:\Path\To\Git.exe

The next time you attempt to commit to a repository, you'll be prompted to enter your credentials. That should be it. You will not be asked for your credentials any longer until you change your password.

下次尝试提交到存储库时,系统会提示您输入凭据。应该是这样。在您更改密码之前,不会再要求您提供凭据。



Just for your knowledge... Your credentials are stored in the Windows Credential Store

仅供参考...您的凭据存储在 Windows 凭据存储中

Where are you storing my credentials?

This app just uses the existing Windows Credential Store to hold your credentials. You can see the stored credentials by going to Control Panel > User Accounts > Credential Manager and choosing "Windows Credentials". The entries starting "git:" are from git-credential-winstore.

你在哪里存储我的凭据?

此应用程序仅使用现有的 Windows 凭据存储来保存您的凭据。您可以通过转到控制面板 > 用户帐户 > 凭据管理器并选择“Windows 凭据”来查看存储的凭据。以“git:”开头的条目来自 git-credential-winstore。

回答by Grant Limberg

If you set a password for your key file, you'll always need to type in that password when connecting. If you create a passwordless key, then you won't have to type it every time, however, anyone with access to your key file can now connect to your github account.

如果您为密钥文件设置了密码,则在连接时始终需要输入该密码。如果您创建无密码密钥,则不必每次都键入它,但是,任何有权访问您的密钥文件的人现在都可以连接到您的 github 帐户。

ssh-agent may also work. Try running that and see if it will remember your passphrase.

ssh-agent 也可以工作。尝试运行它,看看它是否会记住您的密码。

回答by hwjp

[edit - misread the question, this is an answer to a related problem. leaving rephrased version for posterity]

[编辑 - 误读了问题,这是对相关问题的回答。为后代留下改写的版本]

My case was that I was trying to push to a repo that was hosted on one of our servers. Whenever I tried to do a push, git would ask me for my password (nb - password, not the passphrase to my private key).

我的情况是我试图推送到托管在我们的一台服务器上的存储库。每当我尝试推送时,git 都会询问我的密码(nb - 密码,而不是我的私钥的密码)。

By adding my public key to the authorised keys on the server, I was able to get password-free pushes to that server. And, because there was no passphraseon my private key (which is bad practice btw!) I didn't need to type anything at all in.

通过将我的公钥添加到服务器上的授权密钥,我能够获得对该服务器的无密码推送。而且,因为我的私钥上没有密码(顺便说一句,这是不好的做法!)我根本不需要输入任何内容。

Here's the command to add your public key to a server. It assumes the user gitis the user on the server.

这是将公钥添加到服务器的命令。它假定用户git是服务器上的用户。

cat .ssh/id_rsa.pub | ssh git@GIT_MASTER_IP 'cat >> .ssh/authorized_keys'

You could achieve the same thing by logging onto the server, and manually appending your public key to the file at ~/.ssh/authorized_keys

您可以通过登录服务器并手动将您的公钥附加到文件中来实现相同的目的 ~/.ssh/authorized_keys

回答by roobeedeedada

I realise this is several years overdue, but I stumbled across this question trying to find a solution for it, and I found something that suits all levels of expertise, so I thought I'd share.

我意识到这已经晚了几年,但我偶然发现了这个问题,试图找到解决方案,我找到了适合所有专业水平的东西,所以我想我会分享。

GitHub provide a very helpful installer that makes everything nice and easy: https://help.github.com/articles/caching-your-github-password-in-git/

GitHub 提供了一个非常有用的安装程序,它使一切变得简单易用:https: //help.github.com/articles/caching-your-github-password-in-git/

回答by Nikolay Kotlyarov

Let's assume you'd like to use a pure Git Bashonly solution without using TortoiseGit or PuTTY. Also, you don't want to store your passphrases permanently as it's almost the same as if you would've generated your SSH key without a passphrase in the first place. But you still want to use some caching.

假设您想使用纯Git Bash解决方案而不使用 TortoiseGit 或 PuTTY。此外,您不希望永久存储您的密码,因为这几乎与您首先生成没有密码的 SSH 密钥相同。但是你仍然想使用一些缓存。

For caching purposes ssh-agentprocess is used, which is included with the Git Bash distribution. This process isn't started by default, so it needs to be launched first. For any SSH keys to be cached they should be added to this process with ssh-addcommand which will prompt you for a key's passphrase and store it in memory.

出于缓存目的ssh-agent,使用了进程,它包含在 Git Bash 发行版中。默认情况下不会启动此进程,因此需要先启动它。对于要缓存的任何 SSH 密钥,应使用ssh-add命令将它们添加到此进程中,该命令将提示您输入密钥的密码并将其存储在内存中。

Drawbacks of other solutions:

其他解决方案的缺点:

  • Auto-launching ssh-agentlike in GitHub'sarticle asks for a passphrase right from the start when you launch Git Bash, regardless of whether you'll need to use your SSH key this session or not. If you're working with your local repo today you'll probably want to provide a passphrase only when really needed (e.g. when interacting with a remote repo).
  • If you launch your ssh-agentlike in GitLab'sarticle with eval $(ssh-agent -s)you're probably tired of typing that in each time. Chances are, eventually, you've added those two lines to your .bashrcconfig to auto-launch. Downsides are the same as above plus an extra one: each time you launch a new Git Bash terminal you'll get an extra ssh-agent process (GitHub's bash script checks if that process has already started).
  • Like the two above but especially so when you have separate SSH keys for different hosts, e.g. one for GitHub and another one for GitLab, so providing them all at once is annoying and inconvenient.
  • ssh-agentGitHub文章中的自动启动一样,在您启动 Git Bash 时从一开始就要求输入密码,无论您是否需要在此会话中使用 SSH 密钥。如果您今天正在使用本地存储库,您可能只想在真正需要时(例如,与远程存储库交互时)才提供密码。
  • 如果你ssh-agentGitLab 的文章中启动你的喜欢,eval $(ssh-agent -s)你可能已经厌倦了每次输入。最终,您可能已将这两行添加到您的.bashrc配置中以自动启动。缺点与上述相同,外加一个额外的:每次启动一个新的 Git Bash 终端时,您都会获得一个额外的 ssh-agent 进程(GitHub 的 bash 脚本检查该进程是否已经启动)。
  • 像上面两个一样,但尤其是当您为不同的主机使用单独的 SSH 密钥时,例如一个用于 GitHub,另一个用于 GitLab,因此同时提供它们既烦人又不方便。

So this solution is for those who wonder how to make Git Bash ask for a passphrase only once per Windows session and only when really needed. It resembles the behavior of passphrases management with GnuPG commits auto-signingusing default-cache-ttl.

因此,此解决方案适用于那些想知道如何让 Git Bash 在每个 Windows 会话中仅在真正需要时要求密码短语的人。它类似于密码短语管理使用GnuPG提交行为自动签名使用default-cache-ttl

Configuring SSH to ask for passphrases once, when needed, using Git Bash only

将 SSH 配置为在需要时仅使用 Git Bash 询问一次密码

  1. First, we want to auto-launch the ssh-agentwhen starting a Git Bash shell. We'll use a modified GitHub's scriptfor that as it checks whether the process has already started, but we don't want it to ssh-addkeys right away. This script goes to your ~/.bashrcor ~/.profileor ~/.bash_profile(~is your User's home directory like C:\Users\Username– run cd ~and then pwdfor the Git Bash to print it out):

    ### Start ssh-agent
    
    env=~/.ssh/agent.env
    
    agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
    
    agent_start () {
        (umask 077; ssh-agent >| "$env")  # use -t here for timeout
        . "$env" >| /dev/null ; }
    
    agent_load_env
    
    # agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
    agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
    
    if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
        agent_start
    fi
    
    unset env
    
  2. Now edit or create a ~/.ssh/configfile and add an AddKeysToAgentoption for each host stanza you want caching to be turned on (you can also turn it on globally by placing the directive at the beginning of the file before all the host declarations):

    # GitHub.com
    Host github.com
      Preferredauthentications publickey
      IdentityFile ~/.ssh/id_ed25519_github
      AddKeysToAgent yes
    
    # GitLab.com
    Host gitlab.com
      Preferredauthentications publickey
      IdentityFile ~/.ssh/id_ed25519_gitlab
      AddKeysToAgent yes
    

    From ssh config man page:If this option is set to yes and a key is loaded from a file, the key and its passphrase are added to the agent with the default lifetime, as if by ssh-add(1).

  1. 首先,我们要ssh-agent在启动 Git Bash shell 时自动启动。我们将使用修改后的 GitHub脚本,因为它会检查进程是否已经开始,但我们不希望它立即ssh-add生效。此脚本转到您的~/.bashrcor~/.profile~/.bash_profile~是您的用户的主目录,例如C:\Users\Username- 运行cd ~然后pwd让 Git Bash 将其打印出来):

    ### Start ssh-agent
    
    env=~/.ssh/agent.env
    
    agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
    
    agent_start () {
        (umask 077; ssh-agent >| "$env")  # use -t here for timeout
        . "$env" >| /dev/null ; }
    
    agent_load_env
    
    # agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
    agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
    
    if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
        agent_start
    fi
    
    unset env
    
  2. 现在编辑或创建一个~/.ssh/config文件,并AddKeysToAgent为要打开缓存的每个主机节添加一个选项(您也可以通过将指令放在文件开头的所有主机声明之前来全局打开它):

    # GitHub.com
    Host github.com
      Preferredauthentications publickey
      IdentityFile ~/.ssh/id_ed25519_github
      AddKeysToAgent yes
    
    # GitLab.com
    Host gitlab.com
      Preferredauthentications publickey
      IdentityFile ~/.ssh/id_ed25519_gitlab
      AddKeysToAgent yes
    

    从 ssh 配置手册如果此选项设置为 yes 并且从文件加载密钥,则密钥及其密码短语将添加到具有默认生命周期的代理中,就像通过 ssh-add(1) 一样。

The default maximum lifetime is forever or until the ssh-agentprocess gets killed (either manually from task manager or when your PC is shut down). If you wish to use a finite timeout you can set it with ssh-agent's -tparameter. Change the line in the bash script from the first step above, e.g. for 30 minutes key cache lifetime:

默认的最长生命周期是永远或直到ssh-agent进程被终止(从任务管理器手动或在您的 PC 关闭时)。如果您希望使用有限超时,您可以使用 ssh-agent 的-t参数进行设置。更改上面第一步中 bash 脚本中的行,例如 30 分钟的密钥缓存生存期:

(umask 077; ssh-agent -t 30m >| "$env")

See herefor other time format qualifiers.

有关其他时间格式限定符,请参见此处

回答by Alexander Goncharov

You can create a .bashrcfile in the home directory of your user like C:/Users/youruser, and put there:

您可以.bashrc在用户的主目录中创建一个文件,例如C:/Users/youruser,然后放在那里:

env=~/.ssh/agent.env

agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }

agent_start () {
    (umask 077; ssh-agent >| "$env")
    . "$env" >| /dev/null ; }

agent_load_env

# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)

if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
    agent_start
    ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
    ssh-add
fi

unset env

This script executes every time after bash runs. So you will need to enter the password only once, when git-bashis started!

每次 bash 运行后都会执行此脚本。所以你只需要输入一次密码,什么时候git-bash开始!

Some versions of bash require .bash_profilefile instead .bashrc, so just in case clone .bashrc:

某些版本的 bash 需要.bash_profilefile .bashrc,所以以防万一克隆.bashrc

copy .bashrc .bash_profile