如何在执行Git的shell命令时指定私钥SSH密钥
技术背景
在使用Git进行版本控制时,我们常常需要通过SSH协议与远程仓库进行交互。有时候,我们可能有多个SSH密钥,用于不同的账户或仓库,这就需要在执行Git命令时指定特定的私钥SSH密钥。例如,在使用不同的GitHub账户(个人和工作账户)时,每个账户可能对应不同的SSH密钥。
实现步骤
方法一:配置SSH的config文件
- 编辑
~/.ssh/config
文件,添加如下内容:
1 2 3 4 5
| Host gitserv Hostname remote.server.com IdentityFile ~/.ssh/id_rsa.github IdentitiesOnly yes AddKeysToAgent yes
|
- `IdentitiesOnly yes`用于防止SSH默认行为,确保只使用指定的密钥。
- `AddKeysToAgent yes`可避免每次都输入密钥密码。
- 还可以添加`User git`,避免每次都写`git@`。
- 添加或克隆远程仓库:
1 2 3
| git remote add origin git@gitserv:myrepo.git
git clone git@gitserv:myrepo.git
|
- 正常执行Git命令:
1
| git push -v origin master
|
方法二:使用环境变量GIT_SSH_COMMAND
从Git 2.3.0开始,可以使用以下命令:
1
| GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git clone user@host:repo.git
|
方法三:使用core.sshCommand配置
从Git 2.10+开始,可以为每个仓库设置core.sshCommand
:
1 2 3 4 5 6
| git -c core.sshCommand="ssh -i private_key_file" clone host:repo.git
cd <repo or submodule you just cloned> git config core.sshCommand "ssh -i private_key_file"
|
方法四:使用SSH代理
1
| ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'
|
核心代码
SSH配置文件示例
1 2 3 4 5 6 7 8 9
| Host github.com HostName github.com IdentityFile /path/to/your/personal/github/private/key User dandv
Host github-work HostName github.com IdentityFile /path/to/your/work/github/private/key User workuser
|
使用core.sshCommand配置示例
1
| git config core.sshCommand 'ssh -i private_key_file -o IdentitiesOnly=yes'
|
SSH代理示例
1
| ssh-agent bash -c 'ssh-add /somewhere/yourkey; git clone [email protected]:user/project.git'
|
最佳实践
多账户管理
如果需要管理多个GitHub账户(个人和工作账户),可以在~/.ssh/config
文件中分别配置不同的密钥:
1 2 3 4 5 6 7 8 9
| Host github.com HostName github.com IdentityFile /path/to/your/personal/github/private/key User personaluser
Host github-work HostName github.com IdentityFile /path/to/your/work/github/private/key User workuser
|
克隆个人仓库时使用git clone [email protected]:personaluser/repo.git
,克隆工作仓库时使用git clone git@github-work:workuser/repo.git
。
简化命令
可以在.zshrc
或.bashrc
中添加别名,简化命令:
1
| alias git.key1="git config core.sshCommand 'ssh -i <absolute path to private key>'"
|
常见问题
SSH权限被拒绝错误
如果在运行git push
、pull
或fetch
等命令时遇到SSH权限被拒绝错误,即使已经将SSH公钥复制到GitHub,可使用以下命令:
1
| git config --add --local core.sshCommand 'ssh -i /path-to-ssh-private-key'
|
密钥不生效问题
如果创建的SSH密钥在将.pub
文件添加到GitHub,私钥放在默认目录后仍不生效,可以使用以下命令排查:
该命令的输出会显示Git查找的SSH密钥名称,可以根据输出创建相应名称的密钥,或使用上述方法指定需要的密钥。