Bootstrap

git 指定ssh key

在git clone操作中指定SSH密钥,可以通过以下几种方法实现:

1 使用–config选项在克隆时指定密钥

当你克隆一个git仓库时,可以直接在命令中指定要使用的ssh密钥。这种方法适用于一次性操作,不需要修改全局或仓库级别的配置

git clone [email protected]:用户名/仓库名.git --config core.sshcommand="ssh -i ~/.ssh/rsa_github"

在这个命令中,–config core.sshcommand="ssh -i /.ssh/rsa_github"指定了使用/.ssh/rsa_github作为ssh密钥文件。

2 1修改已克隆仓库的.git/config文件

如果你已经克隆了一个仓库,但想要指定不同的ssh密钥,可以修改仓库目录下的.git/config文件。

打开.git/config文件。
在[core]部分添加或修改sshcommand选项,指定密钥文件路径。

[core]
sshcommand = ssh -i ~/.ssh/rsa_github

同时,你可能还需要修改远程仓库的url,以确保它使用ssh协议而不是https。

[remote "origin"]
url = ssh://[email protected]:用户名/仓库名.git

3 使用ssh-agent和ssh-add命令

如果你希望在使用git命令时自动加载特定的ssh密钥,可以使用ssh-agent和ssh-add命令。

启动ssh-agent:

eval $(ssh-agent -s)

将你的ssh密钥添加到ssh-agent中:

ssh-add ~/.ssh/rsa_github

添加后,你可以通过ssh-add -l命令查看已添加的密钥列表。

4 配置全局ssh配置

如果你希望为特定的git服务器(如github, gitlab等)指定一个别名,并在该别名下使用特定的ssh密钥,可以编辑你的全局ssh配置文件~/.ssh/config。

打开或创建~/.ssh/config文件。
添加如下配置:

host github.com
    hostname github.com
    user git
    identityfile ~/.ssh/rsa_github

在这个配置中,host指定了别名为github.com,hostname是实际的git服务器地址,user是git用户名,identityfile是指定的ssh密钥文件路径。

使用别名克隆仓库:

git clone [email protected]:用户名/仓库名.git

此时,git将使用你在~/.ssh/config中为该别名指定的ssh密钥。

验证
完成上述任一配置后,你可以通过克隆仓库来验证是否成功指定了ssh密钥。如果克隆成功且没有提示密钥验证错误,则说明配置正确。

git clone [email protected]:用户名/仓库名.git

希望这些方法能帮助你成功地在git clone操作中指定ssh密钥。如果遇到任何问题,请随时检查配置和命令是否正确,并确保ssh密钥文件具有正确的权限设置。

;