一台电脑如何管理多个SSH KEY

需求:一台电脑上(Mac os)管理多个ssh key,可以任意切换,达到多用户(账号)使用不同ssh提交代码。

以下利用gerrit和github账号来做例子。

1、生成ssh key

ssh-keygen -t rsa -C "[email protected]" -f ~/.ssh/id_rsa_github


若一路回车(密码可以不写),这样只会在~/.ssh/ 目录下生成 id_rsa 和 id_rsa.pub 两个文件。为了区分,我们在第一个回车后设置路径:

Enter file in which to save the key (/root/.ssh/id_rsa):~/.ssh/文件名
由此我们分别为gerrit和github生成对应的公钥和私钥,完成后的目录:

id_rsa_gerrit

id_rsa_gerrit.pub

id_rsa_github

id_rsa_github.pub

2、设置ssh key的代理
1、 首先查看代理

ssh-add -l


若提示 

Could not open a connection to your authentication agent.


则系统代理里没有任何key,执行如下操作

exec ssh-agent bash


若系统已经有ssh-key 代理 ,可以删除

ssh-add -D
2、 添加私钥

ssh-add ~/.ssh/id_rsa_gerrit
ssh-add ~/.ssh/id_rsa_github

3、添加公钥
在对应的gerrit和github的ssh管理页面,添加对应的公钥(.pub 文件内容),保存到代码管理服务器。

4、添加和编辑配置文件config
在 ~/.ssh 目录下新建一个config文件

touch ~/.ssh/config


添加内容

# gerrit
Host gerrit.xxxx.com
    HostName gerrit.xxxx.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_gerrit
    user gerrit
 
# github
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_github
    user git


当然也可以利用nano命令来创建和编辑

nano ~/.ssh/config


如此,ssh就会根据登陆的不同域,来读取对应的私钥文件

5、测试

ssh -T [email protected]


若出现

Hi XXX! You've successfully authenticated, but GitHub does not provide shell access.


则表示成功。

若出现

permission denied (publickey)


请检查github的ssh管理里添加的公钥是否正确。

6、其他
提交代码到gerrit失败,报错为

remote: ERROR:  In commit xxxxxxxxxxxxxxxxxxxxxxxx
remote: ERROR:  committer email address [email protected]
remote: ERROR:  does not match your user account.
remote: ERROR:
remote: ERROR:  The following addresses are currently registered:
remote: ERROR:    [email protected]
remote: ERROR:
remote: ERROR:  To register an email address, please visit:
remote: ERROR:  http://xxxx/xxxx


此报错并非你之前设置管理多个ssh出现问题,而是因为你当前git用户信息和你提交代码的服务器注册的用户信息不一致,即服务器检查了你的用户信息,进行了拒绝。
解决方法如下:

step1、 编辑.gitconfig

打开~/.gitconfig文件

将原来的

[user]

    name = aaaaa

    email = [email protected]

改成你当前的

    name = bbbbb

    email = bbbbb@ bbb.com

step2、 更改提交

git commit --amend --author 'bbbbb <bbbbb@ bbb.com>'


当然你也可以这样重新提交

git reset HEAD^
git add -A
git commit -m “xxxx”

猜你喜欢

转载自blog.csdn.net/qq_35255775/article/details/83115451