ssh-key生成小记

前言

本文主要讲解在同一台电脑系统下使用多个SSH key,切换使用多用户提交代码。

创建了不同的 PUBLIC KEY,我们就可以在自己电脑上用不同git账号提交自己的代码啦。

生成 KEY

(1)比如有我们有 aaa,bbb,ccc 三个帐号需要生成不同的 PUBLIC KEY。首先我们先来生成aaa账号的key:

1
2
3
4
5
6
7
8
9
10
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):/root/.ssh/id_rsa_aaa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa_aaa.
Your public key has been saved in /root/.ssh/id_rsa_aaa.pub.
The key fingerprint is:
9b:92:f6:1f:d2:72:bd:72:19:45:42:5f:e4:65:33:64 root@AY140122145815620396Z
The key's randomart image is:
1
2
3
4
5
6
7
8
9
10
11
+--[ RSA 2048]----+
| .. .E=|
| ..o++|
| o. .|
| . |
| S . |
| . + .. |
| + = + .o |
| . o +..o. |
| ...o. |
+-----------------+

通过上面的shell,我们在 /root/.ssh/ 目录下创建 id_rsa_aaa 私钥 和 id_rsa_aaa.pub 公钥。

注意这里,设置路径,如果不设置,默认生成 id_rsa 和 id_rsa.pub。

1
Enter file in which to save the key (/root/.ssh/id_rsa):/root/.ssh/id_rsa_aaa

(2)按照上面的步骤逐个生成 bbb 和 ccc 对应的公钥和私钥

(3)查看系统ssh-key代理,执行如下命令

1
2
$ ssh-add -l
Could not open a connection to your authentication agent.

如果发现上面的提示,说明系统代理里没有任何key,执行如下操作

1
exec ssh-agent bash

如果系统已经有ssh-key 代理 ,执行下面的命令可以删除

1
$ ssh-add -D

(4)把 .ssh 目录下的3个私钥添加的 ssh-agent

1
2
3
$ ssh-add ~/.ssh/id_rsa_aaa
$ ssh-add ~/.ssh/id_rsa_bbb
$ ssh-add ~/.ssh/id_rsa_ccc

依次执行上面三条shell 把三个私钥添加到 ssh-key 代理里面

(5)打开github 或者 开源中国 ssh 管理页面把 对应的公钥提交保存到代码管理服务器 (.pub 结尾)

(6)在 .ssh 目录创建 config 配置文件

1
nano ~/.ssh/config

输入如下配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#aaa (github 配置)
Host aaa
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_aaa
#bbb (开源中国 配置)
Host bbb
HostName git.oschina.net
User git
IdentityFile ~/.ssh/id_rsa_bbb
#ccc
........

(6)记住上面一步 Host 里设置的别名,开始克隆项目,以开源中国为例

git clone git@git.oschina.net:userName/projectName.git
到此为止多个ssh-key 已经可以同时使用.

Sayings

遇到ssh key的问题,是因为刚来公司时,需要往gitlab上公司仓库提交代码,而自己又想在github上玩自己的小项目。

一来二去,发现手动切换账号很笨拙,并且有时候一不小心,就用了github的账号往公司仓库提交代码。

在看了一些资料后,终于把问题解决了,账号随时切换,方便快捷,于是也就把解决的过程记录了下,下次再遇到就可以快速解决问题了。

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!