如何将已生成的SSH密钥添加到Git Bash?

31

我在 D:/keys folder 中保存了一个SSH密钥。我想将其添加到我的git bash中。我找到的所有教程都是关于如何使用gitbash生成SSH密钥并加载到github/gitlab中。我使用puttygen生成了SSH密钥。现在我想将其添加到我的git bash中,以便我可以从远程克隆存储库。我该怎么做?

4个回答

42

在Windows上,您可能需要像这样启动ssh代理

# start the ssh-agent in the background
$ eval $(ssh-agent -s)
> Agent pid 59566

将你的SSH私钥添加到ssh-agent中。如果你用不同的名称创建了你的密钥,或者你要添加的现有密钥具有不同的名称,请在命令中替换id_rsa为您的私钥文件的名称。

$ ssh-add <path/to/key>

在“将你的SSH密钥添加到ssh-agent”下面找到这些信息:https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#adding-your-ssh-key-to-the-ssh-agent


10
可以正常运行,但如何使其永久生效?每次重新启动 Git Bash 都需要重复操作。 - Phate
1
@Phate,你明白如何将此永久添加并在每次重启时重复吗? - Manu
我猜的一种方法是将其添加到.bashrc文件中? - John Doe
@Phate 这个答案很有帮助:https://dev59.com/SaXja4cB1Zd3GeqPXNRf核心思路是在你的 .ssh 文件夹下创建(或更新)一个名为“config”的文件,并针对您的需要添加以下行,例如对于 bitbucket:Host bitbucket.org User yourbitbucketusername IdentityFile ~/.ssh/yourkey - Romano

7

我认为gitbash本身没有任何特定的配置。您需要将密钥放在默认位置~\.ssh/id_rsa,然后它就会被使用。如果您需要将它放在其他地方,可以像在Linux上一样使用配置文件~/.ssh/config

host example.com
 HostName example.com
 IdentityFile ~/.ssh/id_rsa
 User git

别忘了设置权限 chmod 400 ~/.ssh/id_rsa


7
假设你要导入到git bash的私钥文件是 D:/keys folder/myprivatekey,而你的Git安装在D:/Git中(其中有二进制文件git-bash.exe),打开文件D:/Git/etc/ssh/ssh_config
文件中包含以下文本:

...
# StrictHostKeyChecking ask
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# IdentityFile ~/.ssh/id_ecdsa
# IdentityFile ~/.ssh/id_ed25519
# Port 22
...

只需在文件中添加一行并保存即可:

...
# StrictHostKeyChecking ask
IdentityFile "D:/keys folder/myprivatekey"
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# IdentityFile ~/.ssh/id_ecdsa
# IdentityFile ~/.ssh/id_ed25519
# Port 22
...

这样就已经添加了密钥。

在我的情况下,Windows 11上安装了Git Bash在Program Files文件夹下,我要找的文件位于C:\Program Files\Git\etc\ssh\ssh_config。另外,请记得以管理员身份运行Git Bash,否则会受到权限限制。 - José Pulido

0

我能够使用Auto-launching ssh-agent on Git for Windows脚本使得密码短语仅在启动后打开的第一个窗口上提示。但是我发现,当我将其添加到~/.profile~/.bashrc中时,它并不起作用。我需要将其添加到~/.bash_profile才能被Windows上的Git Bash识别和使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接